Exception Handling, Exams of Advanced Computer Programming

Exception in thread main java.lang.Error: Unresolved compilation problems: Unreachable catch block for IOException. It is already handled by the catch ...

Typology: Exams

2022/2023

Uploaded on 03/01/2023

tiuw
tiuw šŸ‡ŗšŸ‡ø

4.7

(18)

286 documents

1 / 37

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Exception Handling
What are Exceptions ?
The traditional approach
Exception handing in Java
Standard exceptions in Java
Multiple catch handlers
Catching multiple exceptions
finally block
Checked vs unchecked exception
Stack trace
Assertion
jconsole
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25

Partial preview of the text

Download Exception Handling and more Exams Advanced Computer Programming in PDF only on Docsity!

Exception Handling

 What are Exceptions?

 The traditional approach

 Exception handing in Java

 Standard exceptions in Java

 Multiple catch handlers

 Catching multiple exceptions

 finally block

 Checked vs unchecked exception

 Stack trace

 Assertion

 jconsole

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.

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 ;

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.

Exception

IOException RuntimeException

ArithmeticException

ArrayIndexOutOfBoundsException

FileNotFoundException

EOFException

Handler for RuntimeException can catch ArithmeticException and ArraryIndexOutOfBoundsException, etc.

IllegalArgumentException

NumberFormatException

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.

class MyDivideByZeroException extends RuntimeException {

public String toString() {

return "Zero denominator used" ;

class MyArrayOutOfBoundsException extends RuntimeException {

private int invalidIndex ;

public MyArrayOutOfBoundsException(int invalidIndex) {

this.invalidIndex = invalidIndex ;

public String toString() {

return String.format("Invalid Array Index: %d", invalidIndex) ;