





























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Exception in thread main java.lang.Error: Unresolved compilation problems: Unreachable catch block for IOException. It is already handled by the catch ...
Typology: Exams
1 / 37
This page cannot be seen from the preview
Don't miss anything!






























What are Exceptions?
ļ¶ We donāt live in a perfect world.
ļ§ there are so many unexpected situations that cause our programs to behave different from our expectations.
ļ¶ Exceptions refer to
ļ§ situations where programs cannot behave normally.
ļ§ any abnormal situation can lead to a incorrect program behavior.
ļ¶ Examples of exceptions
ļ§ Happen to divide integer by zero ļØ it may halt the program
ļ§ Non numeric character is entered when an integer is expected.
ļ§ No available memory space when memory allocation is requested by new.
ļ§ No such file when a program tries to open a file.
The traditional approach to exception handling
ļ¶ Check and handle each exception by if statement.
Problems with the traditional approach
ļ¶ Problem #1: Too much overhead for the exception handling
codes
ļ¶ Problem #2: exception handling codes are interspersed with
normal codes.
ļ¶ Problem #3: artificial codes are used to notify exceptional
situations. double badCode(int a[], int y) { if ( a == null ) { System.out.println("null array") ; return - 1.0; } if (y < 0 || y >= a.length) { System.out.printf("Array index %d is not valid%n", y); return - 2.0 ; } int x = a[y] ; if (x < 0 || x >= a.length) { System.out.printf("Array index %d is not valid%n", x); return - 3.0 ; } int z = a[x] ; if (z == 0) { System.out.println("Error: Denominator is 0"); return - 4.0 ; } return 1 / z ; }
badCode with Exception Handling
public class ExceptionHandling_1 { static double badCode(int a[], int y) throws Exception { try { int x = a [y] ; int z = a[x] ; return 1 / z ; } catch ( Exception e ) { System.out.println("Exception occurred: " + e) ; throw e ; } } public static void main(String[] args) { try { badCode(null, 10) ; } catch ( Exception e) { System.out.println("badCode failed") ; } } }
Exception occurred: java.lang.NullPointerException
badCode failed
badCode with Exception Handling
public class ExceptionHandling_1 { static double badCode(int a[], int y) throws Exception { try { int x = a[ y ] ; int z = a[x] ; return 1 / z ; } catch ( Exception e ) { System.out.println("Exception occurred: " + e) ; throw e ; } } public static void main(String[] args) { try { int[] a = {0, 1, 2} ; badCode(a, 3); } catch ( Exception e) { System.out.println("badCode failed") ; } } }
Exception occurred: java.lang.ArrayIndexOutOfBoundsException : 3
badCode failed
Trace with Exception
public class ExceptionHandling_1 { static double badCode(int a[], int y) throws Exception { try { int x = a[y] ; int z = a[x] ; return 1 / z ; } catch ( Exception e ) { System.out.println("Exception occurred: " + e) ; e.printStackTrace(); throw e ; } } public static void main(String[] args) { try { int[] a = {0, 1, 2} ; badCode(a, 3); } catch ( Exception e) { System.out.println("badCode failed") ; } } }
Exception occurred: java.lang.ArrayIndexOutOfBoundsException: 3
java.lang.ArrayIndexOutOfBoundsException: 3
at ExceptionHandling_1.badCode(ExceptionHandling_1.java:4) at ExceptionHandling_1.main(ExceptionHandling_1.java:18)
badCode failed
You can trace the source of the exception by printStackTrace()
Multiple Catch Handlers
import java.util.Scanner;
public class MultipleCatchHandlers {
public static void main(String[] args) { try { Scanner scanner = new Scanner(System.in) ; int x = scanner.nextInt() ; // can throw java.util.InputMismatchException int[] a = {-1, 0, 1, 2} ; int y = a[x] ; // can throw ArrayIndexOutOfBoundsException int z = a[y] / y ; // can throw ArrayIndexOutOfBoundsException and ArithmeticException } catch ( ArithmeticException e) { System.out.println("Arithmetic exception took place: " + e) ; } catch ( ArrayIndexOutOfBoundsException e) { System.out.println("Array index is invalid: " + e) ; } catch ( java.util.InputMismatchException e) { System.out.println("The given string cannot be converted into an integer: " + e) ; } }
}
Multiple catch blocks can be provided to handle different types of exceptions.
Catch handler for multiple exceptions
ļ¶ Catch handler can catch all the exceptions of its own type and its descendants. Handler for Exception can catch all the exceptions below it.
Handler for RuntimeException can catch ArithmeticException and ArraryIndexOutOfBoundsException, etc.
import java.io.*; public class CatchingMultipleExceptions {
public static void main(String[] args) { try { FileReader fin = new FileReader("employee.txt") ; // can throw FileNotFoundException BufferedReader in = new BufferedReader(fin) ;
int i1 = Integer.parseInt(in.readLine()) ; // can throw NumberFormatException int i2 = Integer.parseInt(in.readLine()) ; // can throw NumberFormatException System.out.printf("%d %d%n ", i1, i2) ;
int[] a = {-10, 0, 10, 20} ; System.out.println(a[i1] / a[i2]) ; // can throw ArrayIndexOutOfBoundsException and ArithmeticException } catch ( IOException e) { // can catch FileNotFoundException System.out.println(e) ; } catch ( RuntimeException e) { // can catch ArrayIndexOutOfBoundsException, ArithmeticException, and NumberFormatException System.out.println(e) ; } } }
2 1 java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 4
Subclasses of Exception
Subclasses of IOException
The finally Block
ļ¶ The finally block always executes when the try block exits.
ļ¶ This ensures that the finally block is executed even if an unexpected exception occurs import java.io.*; import java.util.Vector; public class FinallyBlock { public static void main(String[] args) { Vector vector = new Vector(10) ; PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < 10; i++) out.println("Value at: " + i + " = " + vector.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } } }
Entering try statement Caught ArrayIndexOutOfBoundsException: 0 >= 0 Closing PrintWriter
User-defined Exceptions: definitions
ļ¶ Programmer can define new classes of exceptions by
extending, commonly, the RuntimeException class.