Question

In: Computer Science

Write a try/catch/finally clause to catch one or more specific Exception objects in Java.

Write a try/catch/finally clause to catch one or more specific Exception objects in Java.

Solutions

Expert Solution

Program with its explanation:

Keyword Description
Try Suspicious code that might throws an error and stops the program execution should be written in try block
Catch Exceptions occured in the code are handled by catch blocks; as the name suggests it catches the exceptions
Finally Important code/information in our program that needs to be executed irrespective of whether or not the exception is thrown.
Throw it throw exception explicitly
Throws it does not throw an exception but is used to declare exceptions.

Multiple programs are listed so that you can understand the concept :

Program 1:

public class TryCatchFinally {

   public static void main(String[] args) {
       try
       {
       System.out.println("try block");
       }
       catch (Exception e)
       {
       System.out.println("catch block");
       }
       finally
       {
       System.out.println("finally block");
       }
   }
}

Ouput:

try block
finally block

Explanation: Since there is no suspicious code in try block so catch block doesnt comes into picture.

Program 2:

public class TryCatchFinally {

   public static void main(String[] args) {
       int num1, num2;
       int div;
   try {
  
       Scanner sc =new Scanner(System.in);
       System.out.println("enter num1");
       num1=sc.nextInt();
       System.out.println("enter num2");
       num2=sc.nextInt();
  
       System.out.println("num1/num2 is="+num1+"/"+num2);
   div = num1 / num2; // anything divided by zero is infinite so it is going to throw exception
   System.out.println("result is="+div);
   System.out.println("end of try block");
   }
   catch (ArithmeticException e) {
   // blocks only Arithmetic exception occurs in try block
   System.out.println("ArithmeticException Occurred !! You should not divide a number by zero");
   }
   catch (Exception e) {
   // This is a generic Exception handler
   System.out.println("generic Exception occurred !!");
   }
   finally
           {
           System.out.println("finally block");
           }

   }
}
Output:

enter num1
10
enter num2
0
num1/num2 is=10/0
ArithmeticException Occurred !! You should not divide a number by zero
finally block

Program3.1:

public class TryCatchFinally {

   public static void main(String[] args) {
  
           try{
           int a[]=new int[7]; // array of 7 values 0 to 6
           a[1]=10/0;// using second index i.e. 1 and divide by zero throws Arithematic exception
           System.out.println("First print statement in try block");
           }
           catch(ArithmeticException e){
           System.out.println("Warning: ArithmeticException");
           }
           catch(ArrayIndexOutOfBoundsException e){
           System.out.println("Warning: ArrayIndexOutOfBoundsException");
           }
           catch(Exception e){
           System.out.println("Warning: Some Other exception");
           }          
          
   finally
           {
           System.out.println("finally block");
           }

   }
}

Output:

Warning: ArithmeticException
finally block

Program3.2:

import java.io.IOException;
import java.util.Scanner;

import javax.imageio.IIOException;

public class TryCatchFinally {

   public static void main(String[] args) {
  
           try{
           int a[]=new int[7]; // array of 7 values 0 to 6
           a[9]=10/2;// using 10th index i.e. 9 and throws ArrayIndexOutOfBoundsException bcz array if of 7 // values
           System.out.println("First print statement in try block");
           }
           catch(ArithmeticException e){
           System.out.println("Warning: ArithmeticException");
           }
           catch(ArrayIndexOutOfBoundsException e){
           System.out.println("Warning: ArrayIndexOutOfBoundsException");
           }
           catch(Exception e){
           System.out.println("Warning: Some Other exception");
           }          
          
   finally
           {
           System.out.println("finally block");
           }

   }
}

Output:

Warning: ArrayIndexOutOfBoundsException
finally block

Program4:

public class TryCatchFinally {

   public static void main(String[] args) {
  
       try
       {
       System.out.println("try block");
         
       throw new NullPointerException("null occurred");
       }
       catch (NumberFormatException e)
       {
       System.out.println("catch block 1");
       }
       catch (NullPointerException e)
       {
       System.out.println("catch block 2");
       }
       catch (Exception e)
       {
       System.out.println("catch block 3");
       }
       finally
       {
       System.out.println("finally block");
       }
   }
}

Output:

try block
catch block 2
finally block

Explanation: catch block 2 because specific exception was mentioned i.e. nullpointerexception and it goes to specific block. If you comment out Catch2 block then it is going to print

try block
catch block 3
finally block

as generic exception block then catches the exception and prints the code inside it.

Program5:

public class TryCatchFinally {

       public static void main(String[] args) {
      
           try
           {
           System.out.println("try block");
             
           throw new NullPointerException("Null occurred");
           }
           finally
           {
           System.out.println("finally block");
           }
       }
   }


Output:

try block
finally block
Exception in thread "main" java.lang.NullPointerException: Null occurred
   at Threadds.TryCatchFinally.main(TryCatchFinally.java:18)

Explanation: SInce no catch block is there to handle the exception so it is going to throw the exception.

Program6:

public class TryCatchFinally {
   void testMethod(int num) throws IOException, ArithmeticException{
   if(num==1)
   throw new IOException("IOException Occurred");
   else
   throw new ArithmeticException("ArithmeticException");
   }
  
   public static void main(String args[]){
   try{
       TryCatchFinally obj=new TryCatchFinally();
   obj.testMethod(1);
   }catch(Exception ex){
   System.out.println(ex);
   }
   }
   }

Output:

java.io.IOException: IOException Occurred

Explanation: If   obj.testMethod(2); is written it gives output as  java.lang.ArithmeticException: ArithmeticException
as it is defining exceptions explicitly.

Program7:

public class TryCatchFinally {

   public static void main(String[] args) {
       int num1, num2;
       int div;
   try {
  
       Scanner sc =new Scanner(System.in);
       System.out.println("enter num1");
       num1=sc.nextInt();
       System.out.println("enter num2");
       num2=sc.nextInt();
  
       System.out.println("num1/num2 is="+num1+"/"+num2);
   div = num1 / num2;
   System.out.println("result is="+div);
   System.out.println("end of try block");
   }
   catch (ArithmeticException e) {
   System.out.println("You should not divide a number by zero");
   e.printStackTrace();
   }
   catch (Exception e) {
   System.out.println("Exception occurred");
   e.printStackTrace();
   }
   finally
           {
           System.out.println("finally block");
           }

   }
}
Output:

enter num1
10
enter num2
0
num1/num2 is=10/0
You should not divide a number by zero
finally block
java.lang.ArithmeticException: / by zero
   at Threadds.TryCatchFinally.main(TryCatchFinally.java:23)

Explanation: e.printStackTrace(); is a method of Java’s throwable class which prints the throwable along with other details like the line number and class name where the exception occurred.

NOTE: Please add necessary import statements to execute the program smoothly.


Related Solutions

Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter...
Raising an Exception In the previous problem, you used a try/except statement to catch an exception....
Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.) Write a function...
What is Try and Catch in Java with example?
What is Try and Catch in Java with example?
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are...
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are it's benefits? What does it mean when we raise a custom exception?
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code i have in POWERSHELL: while($true) { $input= Read-Host "Enter the option 1-5" if ($input -eq 5) { break } #B. Create a “switch” statement that continues to prompt a user by doing each of the following activities, until a user presses key 5: switch ( $input ){ #Using a regular expression, list files within the Requirements1 folder, with the .log file extension and redirect...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try and catch" statement to catch an exception if "empStatus == 1" hourly wage is not between $15.00/hr. and $25.00/hr. The keywords “throw” and “throws” MUST be used correctly and both keywords can be used either in a constructor or in a method. If an exception is thrown, the program code should prompt the user for the valid input and read it in. *NOTE*- I...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] =...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] = 0;} catch(ArithmeticException e){array[2] = 0} // ? finally{ return 0;}} Could you please tell me why the line with the question mark will not report an error?
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a  ...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to   be   thrown   when   a   string   is   discovered   that   has   too   many   characters   in   it. Consider   a   program   that   takes   in   the   last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,  ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT