Exception Handling Hands-Ons [Java > Exception Handling] | Accenture TFA Training Pre-Learning Modules

0

Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.

Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).

All Question of the Hands-On Present Below for Ease Use Ctrl + F with the question name to find the Question. All the Best!


1.Array Manipulation - Use try with multi catch

PAth: JAVA/Exception Handling/Array Manipulation - Use try with multi catch/ArrayException.java

import java.util.*;

public class ArrayException {

    public int size,index;

    public int arr[];

    public String getPriceDetails()

    {

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter the number  of elements in the array");

        try {

            size=sc.nextInt();

            size=Integer.parseInt(String.valueOf(size));

            arr=new int[size];

            System.out.println("Enter the price details");

            for(int i=0;i<size;i++)

            {

                arr[i]=sc.nextInt();

            }

            System.out.println("Enter the index of the array element you want to access");

            index=sc.nextInt();

            return("The array element is "+arr[index]);

        

        }

        catch(ArrayIndexOutOfBoundsException e)

        {

            return("Array index is out of range");

        }

        catch(InputMismatchException e)

        {

            return("Input was not in the correct format");

        }

    }

    public static void main(String args[])

    {

        Scanner sc=new Scanner(System.in);

        ArrayException ex=new ArrayException();

        System.out.println(ex.getPriceDetails());

    }

}


2. Calculate Product cost - Try with multiple catch

Path: JAVA/Exception Handling/Calculate Product cost - Try with multiple catch/Main.java

import java.util.*;


public class Main {


public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

try {

    System.out.println("Enter the total cost of photo frames");

    int tot=sc.nextInt();

    System.out.println("Enter the number of photo frames");

    int n=sc.nextInt();

    int cost=tot/n;

    System.out.println("Cost of each photo frame is "+cost);

    

} catch(InputMismatchException e) {

    System.out.println("InputMismatchException : Input should be an integer");

catch(ArithmeticException e)

{

    System.out.println("ArithmeticException : Cannot divide by zero");

}

    //FILL THE CODE

}


}


3. Display Array element - Usage of finally

Path: JAVA/Exception Handling/Display Array element - Usage of finally/Main.java

import java.util.Scanner;


public class Main {


public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String[] str=new String[5];

for(int i=0;i<5;i++)

{     

    str[i]=sc.nextLine();

}

int n=sc.nextInt();

try{

    System.out.println(str[n]);

}

catch(ArrayIndexOutOfBoundsException e)

{

    System.out.println("Index is out of bounds of the array");

}

finally

{

    System.out.println("Thank you Have a nice day");

}

}

}


4. Display Product Details - User defined Exception

Path: JAVA/Exception Handling/Display Product Details - User defined Exception/InvalidPriceException.java

import java.util.*;

//This class should inherit Exception class

public class InvalidPriceException extends Exception

{   

    //Provide a single argument constructor

    public InvalidPriceException(String s)

    {   

    }  

}


Path: JAVA/Exception Handling/Display Product Details - User defined Exception/Main.java

import java.util.*;


public class Main {

    

    static void validate(int price) throws InvalidPriceException

    {

        if(price<100)

        throw new InvalidPriceException("InvalidPriceException");

    }

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter product name");

String str=sc.nextLine();

System.out.println("Enter price");

try {

    int n=sc.nextInt();

    validate(n);

    System.out.println("Name : "+str);

    System.out.println("Price : "+n);

catch(InvalidPriceException e) {

System.out.println(e+" - Product price invalid");

    //FILL THE CODE

}

}

}


5. Divide two numbers - Use finnally

Path: JAVA/Exception Handling/Divide two numbers - Use finally/Division.java

import java.util.*;


public class Division{

    

    public String divideTwoNumbers(int number1, int number2){

        String str="";

        int res;

        try{

            res=number1/number2;

            str="The answer is "+Integer.toString(res);

        }

        catch (ArithmeticException e){

            str="Division by zero is not possible";

        }

        finally{

            str=str.concat(". Thanks for using the application.");

            return str;

        }

    }

    

    public static void main (String[] args) {

        

        Scanner sc=  new Scanner(System.in);

        Division obj = new Division();

        System.out.println("Enter the numbers");

        int a=sc.nextInt();

        int b=sc.nextInt();

        System.out.println(obj.divideTwoNumbers(a,b));

    }

}


6. Fund Transfer

Path: JAVA/Exception Handling/Fund Transfer/Account.java

public class Account {

private long accountNo;

private double balance;

public long getAccountNo() {

return accountNo;

}

public void setAccountNo(long accountNo) {

this.accountNo = accountNo;

}

public double getBalance() {

return balance;

}

public void setBalance(double balance) {

this.balance = balance;

}

public Account(){}

public void fundTransfer(long beneficiaryAccountNo, String ifscCode, double amtTobeTransferred) throws InvalidIFSCCodeException//Fill the exception

{

//FILL CODE

if(ifscCode.length()==11 && ifscCode.matches("[A-Z]{4}[0-9]{7}")){

    balance=balance-amtTobeTransferred;

}else

  throw new InvalidIFSCCodeException("Invalid IFSCCode");

}

}


Path: JAVA/Exception Handling/Fund Transfer/InvalidIFSCCodeException.java

public class InvalidIFSCCodeException extends Exception {

//Fill code

public InvalidIFSCCodeException(String message ){

    super (message);

}

}


Path: JAVA/Exception Handling/Fund Transfer/Main.java

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter the account no:");

long accountNo=sc.nextLong();

System.out.println("Enter the balance amount:");

double balance=sc.nextDouble();

System.out.println("Enter the beneficiary accountno:");

long beneficiaryAccNo=sc.nextLong();

System.out.println("Enter the amount to be transferred:");

double amtTobeTransferred=sc.nextDouble();

System.out.println("Enter the IFSC code:");

String ifscCode=sc.next();

//Fill Code

Account a=new Account();

a.setAccountNo(accountNo);

a.setBalance(balance);

try{

    a.fundTransfer(accountNo, ifscCode, amtTobeTransferred);

    System.out.println("Transaction completed successfully. The balance amount in your account is:"+String.format("%.1f",a.getBalance()));

}catch(InvalidIFSCCodeException e){

    System.out.println("InvalidIFSCCodeException: "+e.getMessage());

}

}

}


7. Get Input and handle exception

Path: JAVA/Exception Handling/Get Input and handle exception/Main.java

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

try {

    int n=sc.nextInt();

    System.out.println("The input is "+n);

catch(InputMismatchException e) {

    System.out.println("Input should be a number");

    //FILL THE CODE

}

}


8. Marathon Registration

Path: JAVA/Exception Handling/Marathon Registration/Marathon Registration/Main.java

import java.util.*;

public class Main {

    static String name;

    static int age;

    static char gender;

    static long contact;

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);

Marathon m=new Marathon();

while(true)

{

System.out.println("Enter name: ");

    try{

        name=sc.next();

        if(!name.matches("^[a-zA-Z]*$"))

        {

            throw new InputMismatchException();

        }

    }

    catch(InputMismatchException i)

    {

        System.out.println("Invalid Input");

        break;

    }

System.out.println("Enter age: ");

try{

    age=sc.nextInt();

}

catch(InputMismatchException i)

{

    System.out.println("Invalid Input");

    break;

}

        System.out.println("Enter Gender: ");

    try{

        gender=sc.next().charAt(0);

        if(!(gender=='m' || gender=='f' || gender=='M' || gender=='F'))

        {

            throw new InputMismatchException();

        }

    }

    catch(InputMismatchException i)

    {

        System.out.println("Invalid Input");

        break;

    }

System.out.println("Enter Contact no: ");

try{

    contact=sc.nextLong();

}

catch(InputMismatchException i)

{

    System.out.println("Invalid Input");

    break;     

}

//Fill the code

m.setName(name);

m.setAge(age);

m.setGender(gender);

m.setContactNo(contact);

System.out.println("Registered Successfully");

break;

}

}

}


Path: JAVA/Exception Handling/Marathon Registration/Marathon Registration/Marathon.java

public class Marathon {

private String name;

private int age;

private char gender;

private long contactNo;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public char getGender() {

return gender;

}

public void setGender(char gender) {

this.gender = gender;

}

public long getContactNo() {

return contactNo;

}

public void setContactNo(long contactNo) {

this.contactNo = contactNo;

}

public Marathon(){}

}


9. Register a Candidate - User defined Exception(with throw and throws)

Path: JAVA/Exception Handling/Register a Candidate - User defined Exception(with throw and throws)/Candidate.java

public class Candidate {

private String name;

private String gender;

private double expectedSalary;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public double getExpectedSalary() {

return expectedSalary;

}

public void setExpectedSalary(double expectedSalary) {

this.expectedSalary = expectedSalary;

}

}


Path: JAVA/Exception Handling/Register a Candidate - User defined Exception(with throw and throws)/InvalidSalaryException.java

public class InvalidSalaryException extends Exception{

    public InvalidSalaryException(String s)

    {

        super(s);

    }

}


Path: JAVA/Exception Handling/Register a Candidate - User defined Exception(with throw and throws)/Main.java

import java.util.*;

public class Main 

{

    public static Candidate getCandidateDetails() throws InvalidSalaryException

    {

        System.out.println("Enter the candidate Details");

        Scanner sc=new Scanner(System.in);

        Candidate cand=new Candidate();

        System.out.println("Name");

        String name=sc.nextLine();

        cand.setName(name);

        System.out.println("Gender");

        String gender=sc.nextLine();

        cand.setGender(gender);

        System.out.println("Expected Salary");

        double sal=sc.nextDouble();

        if(sal<10000)

        {

            throw new InvalidSalaryException("Registration Failed. Salary cannot be less than 10000.");

        }

        else

        {

            cand.setExpectedSalary(sal);

            return cand;

        }

    }

    public static void main(String args[])

    {

        Main exp=new Main();

        Candidate exp2;

        try

        {

            exp2=exp.getCandidateDetails();

            System.out.println("Registration Successful");

        }

        catch(InvalidSalaryException e)

        {

            System.out.println(e.getMessage());

        }

    }

}


10. Simple Calculator

Path: JAVA/Exception Handling/Simple Calculator/Calculator.java

public class Calculator {


private int no1;

private int no2;

private char operation;

public int getNo1() {

return no1;

}

public void setNo1(int no1) {

this.no1 = no1;

}

public int getNo2() {

return no2;

}

public void setNo2(int no2) {

this.no2 = no2;

}

public char getOperation() {

return operation;

}

public void setOperation(char operation) {

this.operation = operation;

}

public int performCalculation()

{

int result=0;

//fill the code

try{

    switch(operation){

        case '+':

            result=no1+no2;

            break;

        case '-':

            result=no1-no2;

            break;

        case '*':

            result=no1*no2;

            break;

        case '/':

            result=no1/no2;

            break;

    }

}catch(ArithmeticException e){

    result=-1;

}finally{

    no1=0;

    no2=0;

}

return result;

}

public Calculator(){}

}


Path: JAVA/Exception Handling/Simple Calculator/Main.java

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);

System.out.println("Enter Number 1:");

int no1=sc.nextInt();

System.out.println("Enter Number 2:");

int no2=sc.nextInt();

System.out.println("Type of operation:");

String op=sc.next();

char ope=op.charAt(0);

    //FILL THE CODE

        Calculator cal=new Calculator();

        cal.setNo1(no1);

        cal.setNo2(no2);

        cal.setOperation(ope);

        int result=cal.performCalculation();

        System.out.println(result);

        }

}


11. Validate Date using ParseException - Use try catch throws (1)

Path: JAVA/Exception Handling/Validate Date using ParseException - Use try catch throws (1)/Main.java

import java.util.Scanner;

import java.util.*;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.text.DateFormat;


public class Main {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

    //FILL THE CODE

    String dateString=sc.nextLine();

    try {

        Date parsedDate=convertStringToDate(dateString);

        System.out.println(dateString+" is a valid date");

        

    } catch(ParseException e) {

        System.out.println(dateString+" is not a valid date");

    }

}

public static Date convertStringToDate(String str)throws ParseException  {

    DateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");

    Date date=new Date();

    sdf.setLenient(false);

    date=sdf.parse(str);

return date;

}

}



If you have any queries, please feel free to ask on the comment section.

If you want MCQs and Hands-On solutions for any courses, Please feel free to ask on the comment section too.

Please share and support our page!

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !