gestion des exceptions en java - supélec€¦ · gestion des exceptions en java 2a dut...

125
Conception et Programmation Orientées Objet Gestion des Exceptions en Java 2A DUT Informatique - IUT d’Orsay - 11 Octobre 2019 Idir AIT SADOUNE [email protected]

Upload: others

Post on 23-May-2020

35 views

Category:

Documents


1 download

TRANSCRIPT

Conception et Programmation Orientées ObjetGestion des Exceptions en Java

2A DUT Informatique - IUT d’Orsay - 11 Octobre 2019

Idir AIT [email protected]

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

import java.util.Scanner;

public class DivideByZeroNoExceptionHandling{

public static int quotient(int numerator, int denominator){return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);

System.out.print("Please enter an integer numerator: ");int numerator = scanner.nextInt();System.out.print("Please enter an integer denominator: ");int denominator = scanner.nextInt();

int result = quotient(numerator, denominator);System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result);

}}

Please enter an integer numerator: 100Please enter an integer denominator: 7

Result: 100 / 7 = 14

import java.util.Scanner;

public class DivideByZeroNoExceptionHandling{

public static int quotient(int numerator, int denominator){return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);

System.out.print("Please enter an integer numerator: ");int numerator = scanner.nextInt();System.out.print("Please enter an integer denominator: ");int denominator = scanner.nextInt();

int result = quotient(numerator, denominator);System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result);

}}

Please enter an integer numerator: 100Please enter an integer denominator: 7

Result: 100 / 7 = 14

import java.util.Scanner;

public class DivideByZeroNoExceptionHandling{

public static int quotient(int numerator, int denominator){return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);

System.out.print("Please enter an integer numerator: ");int numerator = scanner.nextInt();System.out.print("Please enter an integer denominator: ");int denominator = scanner.nextInt();

int result = quotient(numerator, denominator);System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result);

}}

Please enter an integer numerator: 100Please enter an integer denominator: 0Exception in thread "main" java.lang.ArithmeticException: / by zeroat DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:6)at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:16)

import java.util.Scanner;

public class DivideByZeroNoExceptionHandling{

public static int quotient(int numerator, int denominator){return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);

System.out.print("Please enter an integer numerator: ");int numerator = scanner.nextInt();System.out.print("Please enter an integer denominator: ");int denominator = scanner.nextInt();

int result = quotient(numerator, denominator);System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result);

}}

Please enter an integer numerator: 100Please enter an integer denominator: helloException in thread "main" java.util.InputMismatchExceptionat java.util.Scanner.throwFor(Unknown Source)at java.util.Scanner.next(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:14)

Stack Traceþ In the second and the third executions, the user enters the values 0 and ”hello” as thedenominator. Several lines of information are displayed in response to these invalid inputs.

þ Java does not allow division by zero in integer arithmetic. When this occurs, Java throws anArithmeticException.

þ An InputMismatchException occurs when Scanner method nextInt receives a string that doesnot represent a valid integer.

þ This information is known as a stack trace, which includes the name of the exception(java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurredand the method-call stack (i.e., the call chain) at the time it occurred.

þ The stack trace includes the path of execution that led to the exception method by method.This helps you debug the program.

þWhen exceptions occur and stack traces are displayed, the program also exits.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 6/56

Stack Traceþ In the second and the third executions, the user enters the values 0 and ”hello” as thedenominator. Several lines of information are displayed in response to these invalid inputs.

þ Java does not allow division by zero in integer arithmetic. When this occurs, Java throws anArithmeticException.

þ An InputMismatchException occurs when Scanner method nextInt receives a string that doesnot represent a valid integer.

þ This information is known as a stack trace, which includes the name of the exception(java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurredand the method-call stack (i.e., the call chain) at the time it occurred.

þ The stack trace includes the path of execution that led to the exception method by method.This helps you debug the program.

þWhen exceptions occur and stack traces are displayed, the program also exits.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 6/56

Stack Traceþ In the second and the third executions, the user enters the values 0 and ”hello” as thedenominator. Several lines of information are displayed in response to these invalid inputs.

þ Java does not allow division by zero in integer arithmetic. When this occurs, Java throws anArithmeticException.

þ An InputMismatchException occurs when Scanner method nextInt receives a string that doesnot represent a valid integer.

þ This information is known as a stack trace, which includes the name of the exception(java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurredand the method-call stack (i.e., the call chain) at the time it occurred.

þ The stack trace includes the path of execution that led to the exception method by method.This helps you debug the program.

þWhen exceptions occur and stack traces are displayed, the program also exits.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 6/56

Stack Traceþ In the second and the third executions, the user enters the values 0 and ”hello” as thedenominator. Several lines of information are displayed in response to these invalid inputs.

þ Java does not allow division by zero in integer arithmetic. When this occurs, Java throws anArithmeticException.

þ An InputMismatchException occurs when Scanner method nextInt receives a string that doesnot represent a valid integer.

þ This information is known as a stack trace, which includes the name of the exception(java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurredand the method-call stack (i.e., the call chain) at the time it occurred.

þ The stack trace includes the path of execution that led to the exception method by method.This helps you debug the program.

þWhen exceptions occur and stack traces are displayed, the program also exits.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 6/56

Stack Traceþ In the second and the third executions, the user enters the values 0 and ”hello” as thedenominator. Several lines of information are displayed in response to these invalid inputs.

þ Java does not allow division by zero in integer arithmetic. When this occurs, Java throws anArithmeticException.

þ An InputMismatchException occurs when Scanner method nextInt receives a string that doesnot represent a valid integer.

þ This information is known as a stack trace, which includes the name of the exception(java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurredand the method-call stack (i.e., the call chain) at the time it occurred.

þ The stack trace includes the path of execution that led to the exception method by method.This helps you debug the program.

þWhen exceptions occur and stack traces are displayed, the program also exits.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 6/56

Stack Traceþ In the second and the third executions, the user enters the values 0 and ”hello” as thedenominator. Several lines of information are displayed in response to these invalid inputs.

þ Java does not allow division by zero in integer arithmetic. When this occurs, Java throws anArithmeticException.

þ An InputMismatchException occurs when Scanner method nextInt receives a string that doesnot represent a valid integer.

þ This information is known as a stack trace, which includes the name of the exception(java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurredand the method-call stack (i.e., the call chain) at the time it occurred.

þ The stack trace includes the path of execution that led to the exception method by method.This helps you debug the program.

þWhen exceptions occur and stack traces are displayed, the program also [email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 6/56

Exception Handling

þ An exception is an indication of a problem that occurs during a program’s execution.

þ In many cases, handling an exception allows a program to continute executing as if no problemhad been encountered.

þ Exception handling enables you to create applications that can resolve (or handle) exceptions.

Aim of this course

The features presented in this chapter help you write robust and fault-tolerant programs that candeal with problems and continue executing or terminate gracefully.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 7/56

Exception Handling

þ An exception is an indication of a problem that occurs during a program’s execution.

þ In many cases, handling an exception allows a program to continute executing as if no problemhad been encountered.

þ Exception handling enables you to create applications that can resolve (or handle) exceptions.

Aim of this course

The features presented in this chapter help you write robust and fault-tolerant programs that candeal with problems and continue executing or terminate gracefully.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 7/56

Exception Handling

þ An exception is an indication of a problem that occurs during a program’s execution.

þ In many cases, handling an exception allows a program to continute executing as if no problemhad been encountered.

þ Exception handling enables you to create applications that can resolve (or handle) exceptions.

Aim of this course

The features presented in this chapter help you write robust and fault-tolerant programs that candeal with problems and continue executing or terminate gracefully.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 7/56

Exception Handling

þ An exception is an indication of a problem that occurs during a program’s execution.

þ In many cases, handling an exception allows a program to continute executing as if no problemhad been encountered.

þ Exception handling enables you to create applications that can resolve (or handle) exceptions.

Aim of this course

The features presented in this chapter help you write robust and fault-tolerant programs that candeal with problems and continue executing or terminate gracefully.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 7/56

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

import java.util.InputMismatchException;import java.util.Scanner;

public class DivideByZeroWithExceptionHandling{

public static int quotient(int numerator, int denominator) throws ArithmeticException{return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);boolean continueLoop = true;

do{try{System.out.print("Please enter an integer numerator: ");int numerator = scanner.nextInt();System.out.print("Please enter an integer denominator: ");int denominator = scanner.nextInt();

int result = quotient(numerator, denominator);System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result);continueLoop = false;

}...

} while (continueLoop);}

}

import java.util.InputMismatchException;import java.util.Scanner;

public class DivideByZeroWithExceptionHandling{

public static int quotient(int numerator, int denominator) throws ArithmeticException{return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);boolean continueLoop = true;

do{try{...

}catch (InputMismatchException inputMismatchException){System.err.printf("%nException: %s%n", inputMismatchException);scanner.nextLine();System.out.printf("You must enter integers. Please try again.%n%n");

}catch (ArithmeticException arithmeticException){System.err.printf("%nException: %s%n", arithmeticException);System.out.printf("Zero is an invalid denominator. Please try again.%n%n");

}} while (continueLoop);

}}

Please enter an integer numerator: 100Please enter an integer denominator: 0

Exception: java.lang.ArithmeticException: / by zeroZero is an invalid denominator. Please try again.

Please enter an integer numerator: 100Please enter an integer denominator: hello

Exception: java.util.InputMismatchExceptionYou must enter integers. Please try again.

Please enter an integer numerator: 100Please enter an integer denominator: 7

Result: 100 / 7 = 14

Try Block and Catching Exceptions (1/2)

try{...

}catch (ExceptionType exceptionObject){...

}

þ The try block and its corresponding catch blocks form a try statement.

þ The try block encloses the code that might throw an exception and the code that should notexecute if an exception occurs (i.e., if an exception occurs, the remaining code in the try block willbe skipped).

þ A catch block (also called a catch clause or exception handler) catches and handles anexception. It specifies in parentheses an exception parameter that identifies the exception typethe handler can process.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 12/56

Try Block and Catching Exceptions (1/2)

try{...

}catch (ExceptionType exceptionObject){...

}

þ The try block and its corresponding catch blocks form a try statement.

þ The try block encloses the code that might throw an exception and the code that should notexecute if an exception occurs (i.e., if an exception occurs, the remaining code in the try block willbe skipped).

þ A catch block (also called a catch clause or exception handler) catches and handles anexception. It specifies in parentheses an exception parameter that identifies the exception typethe handler can process.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 12/56

Try Block and Catching Exceptions (1/2)

try{...

}catch (ExceptionType exceptionObject){...

}

þ The try block and its corresponding catch blocks form a try statement.

þ The try block encloses the code that might throw an exception and the code that should notexecute if an exception occurs (i.e., if an exception occurs, the remaining code in the try block willbe skipped).

þ A catch block (also called a catch clause or exception handler) catches and handles anexception. It specifies in parentheses an exception parameter that identifies the exception typethe handler can process.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 12/56

Try Block and Catching Exceptions (2/2)

þWhen an exception occurs in a try block, the catch block that executes is the first one whosetype matches the type of the exception that occurred (i.e., the type in the catch block matchesthe thrown exception type exactly or is a direct or indirect superclass of it).

þ The exception parameter’s name enables the catch block to interact with a caught exceptionobject.

þ If a catch handler is written to catch superclass exception objects, it can also catch all objectsof that class’s subclasses.

þ If multiple catch blocks match a particular exception type, only the first matching catch blockexecutes when an exception of that type occurs.

þ It’s a compilation error to catch the exact same type in two different catch blocks associatedwith a particular try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 13/56

Try Block and Catching Exceptions (2/2)

þWhen an exception occurs in a try block, the catch block that executes is the first one whosetype matches the type of the exception that occurred (i.e., the type in the catch block matchesthe thrown exception type exactly or is a direct or indirect superclass of it).

þ The exception parameter’s name enables the catch block to interact with a caught exceptionobject.

þ If a catch handler is written to catch superclass exception objects, it can also catch all objectsof that class’s subclasses.

þ If multiple catch blocks match a particular exception type, only the first matching catch blockexecutes when an exception of that type occurs.

þ It’s a compilation error to catch the exact same type in two different catch blocks associatedwith a particular try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 13/56

Try Block and Catching Exceptions (2/2)

þWhen an exception occurs in a try block, the catch block that executes is the first one whosetype matches the type of the exception that occurred (i.e., the type in the catch block matchesthe thrown exception type exactly or is a direct or indirect superclass of it).

þ The exception parameter’s name enables the catch block to interact with a caught exceptionobject.

þ If a catch handler is written to catch superclass exception objects, it can also catch all objectsof that class’s subclasses.

þ If multiple catch blocks match a particular exception type, only the first matching catch blockexecutes when an exception of that type occurs.

þ It’s a compilation error to catch the exact same type in two different catch blocks associatedwith a particular try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 13/56

Try Block and Catching Exceptions (2/2)

þWhen an exception occurs in a try block, the catch block that executes is the first one whosetype matches the type of the exception that occurred (i.e., the type in the catch block matchesthe thrown exception type exactly or is a direct or indirect superclass of it).

þ The exception parameter’s name enables the catch block to interact with a caught exceptionobject.

þ If a catch handler is written to catch superclass exception objects, it can also catch all objectsof that class’s subclasses.

þ If multiple catch blocks match a particular exception type, only the first matching catch blockexecutes when an exception of that type occurs.

þ It’s a compilation error to catch the exact same type in two different catch blocks associatedwith a particular try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 13/56

Try Block and Catching Exceptions (2/2)

þWhen an exception occurs in a try block, the catch block that executes is the first one whosetype matches the type of the exception that occurred (i.e., the type in the catch block matchesthe thrown exception type exactly or is a direct or indirect superclass of it).

þ The exception parameter’s name enables the catch block to interact with a caught exceptionobject.

þ If a catch handler is written to catch superclass exception objects, it can also catch all objectsof that class’s subclasses.

þ If multiple catch blocks match a particular exception type, only the first matching catch blockexecutes when an exception of that type occurs.

þ It’s a compilation error to catch the exact same type in two different catch blocks associatedwith a particular try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 13/56

Multi-catch

þ It’s relatively common for a try block to be followed by several catch blocks to handle varioustypes of exceptions.

þ If the bodies of several catch blocks are identical, you can use the multi- catch feature to catchthose exception types in a single catch handler and perform the same task.

try{...

}catch (ExceptionType1 | ExceptionType2 | ExceptionType3 | ... exceptionObject){...

}

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 14/56

Multi-catch

þ It’s relatively common for a try block to be followed by several catch blocks to handle varioustypes of exceptions.

þ If the bodies of several catch blocks are identical, you can use the multi- catch feature to catchthose exception types in a single catch handler and perform the same task.

try{...

}catch (ExceptionType1 | ExceptionType2 | ExceptionType3 | ... exceptionObject){...

}

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 14/56

import java.util.InputMismatchException;import java.util.Scanner;

public class DivideByZeroWithExceptionHandling{

public static int quotient(int numerator, int denominator) throws ArithmeticException{return numerator / denominator;

}

public static void main(String[] args){Scanner scanner = new Scanner(System.in);boolean continueLoop = true;

do{try{...

}catch (InputMismatchException | ArithmeticException e){System.err.printf("%nException: %s%n", e);scanner.nextLine();System.out.printf("You must enter a correct integers. Please try again.%n%n");

}} while (continueLoop);

}}

Using the throws Clause

public static int quotient(int numerator, int denominator) throws ArithmeticException{return numerator / denominator;

}

þ Throws clause specifies the exceptions the method might throw if problems occur.

þ Such exceptions may be thrown by statements in the method’s body or by methods calledfrom there.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 16/56

Using the throws Clause

public static int quotient(int numerator, int denominator) throws ArithmeticException{return numerator / denominator;

}

þ Throws clause specifies the exceptions the method might throw if problems occur.

þ Such exceptions may be thrown by statements in the method’s body or by methods calledfrom there.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 16/56

Using the throws Clause

public static int quotient(int numerator, int denominator) throws ArithmeticException{return numerator / denominator;

}

þ Throws clause specifies the exceptions the method might throw if problems occur.

þ Such exceptions may be thrown by statements in the method’s body or by methods calledfrom there.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 16/56

Uncaught Exceptions

þ An uncaught exception is one for which there are no matching catch blocks.

þWhen exceptions occurred, the application terminated early (after displaying the exception’sstack trace).

þ One program can have many threads. If a program has only one thread, an uncaught exceptionwill cause the program to terminate.

þ If a program has multiple threads, an uncaught exception will terminate only the thread inwhich the exception occurred.

þ In such programs, however, certain threads may rely on others, and if one thread terminatesdue to an uncaught exception, there may be adverse effects on the rest of the program.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 17/56

Uncaught Exceptions

þ An uncaught exception is one for which there are no matching catch blocks.

þWhen exceptions occurred, the application terminated early (after displaying the exception’sstack trace).

þ One program can have many threads. If a program has only one thread, an uncaught exceptionwill cause the program to terminate.

þ If a program has multiple threads, an uncaught exception will terminate only the thread inwhich the exception occurred.

þ In such programs, however, certain threads may rely on others, and if one thread terminatesdue to an uncaught exception, there may be adverse effects on the rest of the program.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 17/56

Uncaught Exceptions

þ An uncaught exception is one for which there are no matching catch blocks.

þWhen exceptions occurred, the application terminated early (after displaying the exception’sstack trace).

þ One program can have many threads. If a program has only one thread, an uncaught exceptionwill cause the program to terminate.

þ If a program has multiple threads, an uncaught exception will terminate only the thread inwhich the exception occurred.

þ In such programs, however, certain threads may rely on others, and if one thread terminatesdue to an uncaught exception, there may be adverse effects on the rest of the program.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 17/56

Uncaught Exceptions

þ An uncaught exception is one for which there are no matching catch blocks.

þWhen exceptions occurred, the application terminated early (after displaying the exception’sstack trace).

þ One program can have many threads. If a program has only one thread, an uncaught exceptionwill cause the program to terminate.

þ If a program has multiple threads, an uncaught exception will terminate only the thread inwhich the exception occurred.

þ In such programs, however, certain threads may rely on others, and if one thread terminatesdue to an uncaught exception, there may be adverse effects on the rest of the program.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 17/56

Uncaught Exceptions

þ An uncaught exception is one for which there are no matching catch blocks.

þWhen exceptions occurred, the application terminated early (after displaying the exception’sstack trace).

þ One program can have many threads. If a program has only one thread, an uncaught exceptionwill cause the program to terminate.

þ If a program has multiple threads, an uncaught exception will terminate only the thread inwhich the exception occurred.

þ In such programs, however, certain threads may rely on others, and if one thread terminatesdue to an uncaught exception, there may be adverse effects on the rest of the program.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 17/56

Termination Model of Exception Handling (1/2)

þ If an exception occurs in a try block, the try block terminates immediately and program controltransfers to the first of the following catch blocks in which the exception parameter’s typematches the thrown exception’s type.

þ After the exception is handled, program control does not return to the throw point, becausethe try block has expired (and its local variables have been lost).

þ Rather, control resumes after the last catch block. This is known as the termination model ofexception handling.

þ After executing a catch block, the program’s flow of control proceeds to the first statementafter the last catch block.

þ If no exceptions are thrown in the try block, the catch blocks are skipped and controlcontinues with the first statement after the catch blocks.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 18/56

Termination Model of Exception Handling (1/2)

þ If an exception occurs in a try block, the try block terminates immediately and program controltransfers to the first of the following catch blocks in which the exception parameter’s typematches the thrown exception’s type.

þ After the exception is handled, program control does not return to the throw point, becausethe try block has expired (and its local variables have been lost).

þ Rather, control resumes after the last catch block. This is known as the termination model ofexception handling.

þ After executing a catch block, the program’s flow of control proceeds to the first statementafter the last catch block.

þ If no exceptions are thrown in the try block, the catch blocks are skipped and controlcontinues with the first statement after the catch blocks.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 18/56

Termination Model of Exception Handling (1/2)

þ If an exception occurs in a try block, the try block terminates immediately and program controltransfers to the first of the following catch blocks in which the exception parameter’s typematches the thrown exception’s type.

þ After the exception is handled, program control does not return to the throw point, becausethe try block has expired (and its local variables have been lost).

þ Rather, control resumes after the last catch block. This is known as the termination model ofexception handling.

þ After executing a catch block, the program’s flow of control proceeds to the first statementafter the last catch block.

þ If no exceptions are thrown in the try block, the catch blocks are skipped and controlcontinues with the first statement after the catch blocks.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 18/56

Termination Model of Exception Handling (1/2)

þ If an exception occurs in a try block, the try block terminates immediately and program controltransfers to the first of the following catch blocks in which the exception parameter’s typematches the thrown exception’s type.

þ After the exception is handled, program control does not return to the throw point, becausethe try block has expired (and its local variables have been lost).

þ Rather, control resumes after the last catch block. This is known as the termination model ofexception handling.

þ After executing a catch block, the program’s flow of control proceeds to the first statementafter the last catch block.

þ If no exceptions are thrown in the try block, the catch blocks are skipped and controlcontinues with the first statement after the catch blocks.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 18/56

Termination Model of Exception Handling (1/2)

þ If an exception occurs in a try block, the try block terminates immediately and program controltransfers to the first of the following catch blocks in which the exception parameter’s typematches the thrown exception’s type.

þ After the exception is handled, program control does not return to the throw point, becausethe try block has expired (and its local variables have been lost).

þ Rather, control resumes after the last catch block. This is known as the termination model ofexception handling.

þ After executing a catch block, the program’s flow of control proceeds to the first statementafter the last catch block.

þ If no exceptions are thrown in the try block, the catch blocks are skipped and controlcontinues with the first statement after the catch blocks.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 18/56

Termination Model of Exception Handling (2/2)

þ As with any other block of code, when a try block terminates, local variables declared in theblock go out of scope and are no longer accessible ; thus, the local variables of a try block are notaccessible in the corresponding catch blocks.

þWhen a catch block terminates, local variables declared within the catch block (including theexception parameter of that catch block) also go out of scope and are destroyed.

þ Any remaining catch blocks in the try statement are ignored, and execution resumes at the firstline of code after the try ... catch sequence (this will be a finally block, if one is present).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 19/56

Termination Model of Exception Handling (2/2)

þ As with any other block of code, when a try block terminates, local variables declared in theblock go out of scope and are no longer accessible ; thus, the local variables of a try block are notaccessible in the corresponding catch blocks.

þWhen a catch block terminates, local variables declared within the catch block (including theexception parameter of that catch block) also go out of scope and are destroyed.

þ Any remaining catch blocks in the try statement are ignored, and execution resumes at the firstline of code after the try ... catch sequence (this will be a finally block, if one is present).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 19/56

Termination Model of Exception Handling (2/2)

þ As with any other block of code, when a try block terminates, local variables declared in theblock go out of scope and are no longer accessible ; thus, the local variables of a try block are notaccessible in the corresponding catch blocks.

þWhen a catch block terminates, local variables declared within the catch block (including theexception parameter of that catch block) also go out of scope and are destroyed.

þ Any remaining catch blocks in the try statement are ignored, and execution resumes at the firstline of code after the try ... catch sequence (this will be a finally block, if one is present).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 19/56

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

Finally Block

try{...

}catch (ExceptionType exceptionObject){...

}finally{...

}

þ The finally block, sometimes referred to as the finally clause, is optional.

þ If it’s present, it’s placed after the last catch block. If there are no block, if present, immediatelyfollows the try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 21/56

Finally Block

try{...

}catch (ExceptionType exceptionObject){...

}finally{...

}

þ The finally block, sometimes referred to as the finally clause, is optional.

þ If it’s present, it’s placed after the last catch block. If there are no block, if present, immediatelyfollows the try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 21/56

public class UsingExceptions{public static void main(String[] args){try{throwException();

}catch (Exception exception){System.err.println("Exception handled in main");

}doesNotThrowException();

}public static void throwException() throws Exception{try{System.out.println("Method throwException");throw new Exception();

}catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}finally{System.err.println("Finally executed in throwException");

}}public static void doesNotThrowException(){try{System.out.println("Method doesNotThrowException");

}catch (Exception exception){System.err.println(exception);

}finally{System.err.println("Finally executed in doesNotThrowException");

}System.out.println("End of method doesNotThrowException");

}}

Method throwExceptionException handled in method throwExceptionFinally executed in throwExceptionException handled in mainMethod doesNotThrowExceptionFinally executed in doesNotThrowExceptionEnd of method doesNotThrowException

When the finally Block Executes

þ The finally block will execute whether or not an exception is thrown in the corresponding tryblock.

þ The finally block also will execute if a try block exits by using a return, break or continuestatement or simply by reaching its closing right brace.

þ The one case in which the finally block will not execute is if the application exits early from atry block by calling method System.exit (This method immediately terminates an application).

þ If an exception that occurs in a try block cannot be caught by one of that try block’s catchhandlers, the program skips the rest of the try block and control proceeds to the finally block.

þ If a catch block throws an exception, the finally block still executes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 24/56

When the finally Block Executes

þ The finally block will execute whether or not an exception is thrown in the corresponding tryblock.

þ The finally block also will execute if a try block exits by using a return, break or continuestatement or simply by reaching its closing right brace.

þ The one case in which the finally block will not execute is if the application exits early from atry block by calling method System.exit (This method immediately terminates an application).

þ If an exception that occurs in a try block cannot be caught by one of that try block’s catchhandlers, the program skips the rest of the try block and control proceeds to the finally block.

þ If a catch block throws an exception, the finally block still executes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 24/56

When the finally Block Executes

þ The finally block will execute whether or not an exception is thrown in the corresponding tryblock.

þ The finally block also will execute if a try block exits by using a return, break or continuestatement or simply by reaching its closing right brace.

þ The one case in which the finally block will not execute is if the application exits early from atry block by calling method System.exit (This method immediately terminates an application).

þ If an exception that occurs in a try block cannot be caught by one of that try block’s catchhandlers, the program skips the rest of the try block and control proceeds to the finally block.

þ If a catch block throws an exception, the finally block still executes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 24/56

When the finally Block Executes

þ The finally block will execute whether or not an exception is thrown in the corresponding tryblock.

þ The finally block also will execute if a try block exits by using a return, break or continuestatement or simply by reaching its closing right brace.

þ The one case in which the finally block will not execute is if the application exits early from atry block by calling method System.exit (This method immediately terminates an application).

þ If an exception that occurs in a try block cannot be caught by one of that try block’s catchhandlers, the program skips the rest of the try block and control proceeds to the finally block.

þ If a catch block throws an exception, the finally block still executes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 24/56

When the finally Block Executes

þ The finally block will execute whether or not an exception is thrown in the corresponding tryblock.

þ The finally block also will execute if a try block exits by using a return, break or continuestatement or simply by reaching its closing right brace.

þ The one case in which the finally block will not execute is if the application exits early from atry block by calling method System.exit (This method immediately terminates an application).

þ If an exception that occurs in a try block cannot be caught by one of that try block’s catchhandlers, the program skips the rest of the try block and control proceeds to the finally block.

þ If a catch block throws an exception, the finally block still executes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 24/56

Throwing Exceptions Using the throw Statementpublic static void throwException() throws Exception{try{System.out.println("Method throwException");throw new Exception();

}catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}finally{System.err.println("Finally executed in throwException");

}}

þ The throw statement is executed to indicate that an exception has occurred.

þ You can throw exceptions yourself by using the throw statement.

þ Just as with exceptions thrown by the Java API’s methods, the throw statement indicates toclient applications that an error has occurred.

þ A throw statement specifies an object to be thrown. The operand of a throw can be of anyclass derived from class Throwable.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 25/56

Throwing Exceptions Using the throw Statementpublic static void throwException() throws Exception{try{System.out.println("Method throwException");throw new Exception();

}catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}finally{System.err.println("Finally executed in throwException");

}}

þ The throw statement is executed to indicate that an exception has occurred.

þ You can throw exceptions yourself by using the throw statement.

þ Just as with exceptions thrown by the Java API’s methods, the throw statement indicates toclient applications that an error has occurred.

þ A throw statement specifies an object to be thrown. The operand of a throw can be of anyclass derived from class Throwable.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 25/56

Throwing Exceptions Using the throw Statementpublic static void throwException() throws Exception{try{System.out.println("Method throwException");throw new Exception();

}catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}finally{System.err.println("Finally executed in throwException");

}}

þ The throw statement is executed to indicate that an exception has occurred.

þ You can throw exceptions yourself by using the throw statement.

þ Just as with exceptions thrown by the Java API’s methods, the throw statement indicates toclient applications that an error has occurred.

þ A throw statement specifies an object to be thrown. The operand of a throw can be of anyclass derived from class Throwable.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 25/56

Throwing Exceptions Using the throw Statementpublic static void throwException() throws Exception{try{System.out.println("Method throwException");throw new Exception();

}catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}finally{System.err.println("Finally executed in throwException");

}}

þ The throw statement is executed to indicate that an exception has occurred.

þ You can throw exceptions yourself by using the throw statement.

þ Just as with exceptions thrown by the Java API’s methods, the throw statement indicates toclient applications that an error has occurred.

þ A throw statement specifies an object to be thrown. The operand of a throw can be of anyclass derived from class Throwable.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 25/56

Rethrowing Exceptions

...catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}...

þ Exceptions are rethrown when a catch block, upon receiving an exception, decides either thatit cannot process that exception or that it can only partially process it.

þ Rethrowing an exception defers the exception handling (or perhaps a portion of it) to anothercatch block associated with an outer try statement.

þ An exception is rethrown by using the throw keyword, followed by a reference to theexception object that was just caught.

þ Exceptions cannot be rethrown from a finally block, as the exception parameter (a localvariable) from the catch block no longer exists.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 26/56

Rethrowing Exceptions

...catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}...

þ Exceptions are rethrown when a catch block, upon receiving an exception, decides either thatit cannot process that exception or that it can only partially process it.

þ Rethrowing an exception defers the exception handling (or perhaps a portion of it) to anothercatch block associated with an outer try statement.

þ An exception is rethrown by using the throw keyword, followed by a reference to theexception object that was just caught.

þ Exceptions cannot be rethrown from a finally block, as the exception parameter (a localvariable) from the catch block no longer exists.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 26/56

Rethrowing Exceptions

...catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}...

þ Exceptions are rethrown when a catch block, upon receiving an exception, decides either thatit cannot process that exception or that it can only partially process it.

þ Rethrowing an exception defers the exception handling (or perhaps a portion of it) to anothercatch block associated with an outer try statement.

þ An exception is rethrown by using the throw keyword, followed by a reference to theexception object that was just caught.

þ Exceptions cannot be rethrown from a finally block, as the exception parameter (a localvariable) from the catch block no longer exists.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 26/56

Rethrowing Exceptions

...catch (Exception exception){System.err.println("Exception handled in method throwException");throw exception;

}...

þ Exceptions are rethrown when a catch block, upon receiving an exception, decides either thatit cannot process that exception or that it can only partially process it.

þ Rethrowing an exception defers the exception handling (or perhaps a portion of it) to anothercatch block associated with an outer try statement.

þ An exception is rethrown by using the throw keyword, followed by a reference to theexception object that was just caught.

þ Exceptions cannot be rethrown from a finally block, as the exception parameter (a localvariable) from the catch block no longer exists.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 26/56

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

Portion of class Throwable’s inheritance hierarchy (1/4)

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 28/56

Portion of class Throwable’s inheritance hierarchy (2/4)

þ Only Throwable objects can be used with the exception-handling mechanism.

þ Class Throwable has two direct subclasses : Exception and Error.Class Exception and its subclasses represent exceptional situations that can occur in a Javaprogram and that can be caught by the application.public class ExceptionExample {public static void main(String[] args) {int[] myArray = new int[4];System.out.println(myArray[7]);

}}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7at ExceptionExample.main(ExceptionExample.java:6)

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 29/56

Portion of class Throwable’s inheritance hierarchy (2/4)

þ Only Throwable objects can be used with the exception-handling mechanism.

þ Class Throwable has two direct subclasses : Exception and Error.Class Exception and its subclasses represent exceptional situations that can occur in a Javaprogram and that can be caught by the application.public class ExceptionExample {public static void main(String[] args) {int[] myArray = new int[4];System.out.println(myArray[7]);

}}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7at ExceptionExample.main(ExceptionExample.java:6)

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 29/56

Portion of class Throwable’s inheritance hierarchy (3/4)

Class Error and its subclasses represent abnormal situations that happen in the JVM. MostErrors happen infrequently and should not be caught by applications (it’s usually not possiblefor applications to recover from Errors).public class ErrorExample {public static int factorial(int n) {if(n <= 1) return 1;else return factorial(n-1)*n;

}public static void main(String[] args) {System.out.println(factorial(1_000_000));

}}

Exception in thread "main" java.lang.StackOverflowErrorat ErrorExample.factorial(ErrorExample.java:6)

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 30/56

Portion of class Throwable’s inheritance hierarchy (4/4)

Remark

All Java exception classes inherit directly or indirectly from classException, forming an inheritancehierarchy. (You can extend this hierarchy with your own exception classes).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 31/56

Checked vs. Unchecked Exceptions (1/2)

þ Java distinguishes between checked exceptions and unchecked exceptions.

Checked Exceptions

þ All classes that inherit from class Exception but not directly or indirectly from classRuntimeException are considered to be checked exceptions.

þ Such exceptions are typically caused by conditions that are not under the control of theprogram (for example, in file processing, the program can’t open a file if it does not exist).

þ The compiler checks each method call and method declaration to determine whether themethod throws a checked exception. If so, the compiler verifies that the checked exception iscaught or is declared in a throws clause (this is known as the catch-or-declare requirement).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 32/56

Checked vs. Unchecked Exceptions (1/2)

þ Java distinguishes between checked exceptions and unchecked exceptions.

Checked Exceptions

þ All classes that inherit from class Exception but not directly or indirectly from classRuntimeException are considered to be checked exceptions.

þ Such exceptions are typically caused by conditions that are not under the control of theprogram (for example, in file processing, the program can’t open a file if it does not exist).

þ The compiler checks each method call and method declaration to determine whether themethod throws a checked exception. If so, the compiler verifies that the checked exception iscaught or is declared in a throws clause (this is known as the catch-or-declare requirement).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 32/56

Checked vs. Unchecked Exceptions (1/2)

þ Java distinguishes between checked exceptions and unchecked exceptions.

Checked Exceptions

þ All classes that inherit from class Exception but not directly or indirectly from classRuntimeException are considered to be checked exceptions.

þ Such exceptions are typically caused by conditions that are not under the control of theprogram (for example, in file processing, the program can’t open a file if it does not exist).

þ The compiler checks each method call and method declaration to determine whether themethod throws a checked exception. If so, the compiler verifies that the checked exception iscaught or is declared in a throws clause (this is known as the catch-or-declare requirement).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 32/56

Checked vs. Unchecked Exceptions (1/2)

þ Java distinguishes between checked exceptions and unchecked exceptions.

Checked Exceptions

þ All classes that inherit from class Exception but not directly or indirectly from classRuntimeException are considered to be checked exceptions.

þ Such exceptions are typically caused by conditions that are not under the control of theprogram (for example, in file processing, the program can’t open a file if it does not exist).

þ The compiler checks each method call and method declaration to determine whether themethod throws a checked exception. If so, the compiler verifies that the checked exception iscaught or is declared in a throws clause (this is known as the catch-or-declare requirement).

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 32/56

import java.io.BufferedReader;import java.io.FileReader;

public class CheckedExceptionExample {public static void main(String[] args) {BufferedReader reader = new BufferedReader(new FileReader("fichier.txt"));String line = reader.readLine();while(line != null) {System.out.println(line);line = reader.readLine();

}reader.close();

}}

Unhandled exception type FileNotFoundException

import java.io.BufferedReader;import java.io.FileReader;

public class CheckedExceptionExample {public static void main(String[] args) {BufferedReader reader = new BufferedReader(new FileReader("fichier.txt"));String line = reader.readLine();while(line != null) {System.out.println(line);line = reader.readLine();

}reader.close();

}}

Unhandled exception type FileNotFoundException

Checked vs. Unchecked Exceptions (2/2)

Unchecked Exceptions

þ All exception types that are direct or indirect subclasses of RuntimeException are uncheckedexceptions. These are typically caused by defects in your program’s code.

þ Examples of unchecked exceptions include : ArrayIndexOutOfBoundsExceptions,ArithmeticExceptions, ...

þ Classes that inherit directly or indirectly from classError are unchecked, because Errors aresuch serious problems that your program should not even attempt to deal with them.

þ Unlike checked exceptions, the Java compiler does not examine the code to determinewhether an unchecked exception is caught or declared. Unchecked exceptions typically can beprevented by proper coding.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 34/56

Checked vs. Unchecked Exceptions (2/2)

Unchecked Exceptions

þ All exception types that are direct or indirect subclasses of RuntimeException are uncheckedexceptions. These are typically caused by defects in your program’s code.

þ Examples of unchecked exceptions include : ArrayIndexOutOfBoundsExceptions,ArithmeticExceptions, ...

þ Classes that inherit directly or indirectly from classError are unchecked, because Errors aresuch serious problems that your program should not even attempt to deal with them.

þ Unlike checked exceptions, the Java compiler does not examine the code to determinewhether an unchecked exception is caught or declared. Unchecked exceptions typically can beprevented by proper coding.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 34/56

Checked vs. Unchecked Exceptions (2/2)

Unchecked Exceptions

þ All exception types that are direct or indirect subclasses of RuntimeException are uncheckedexceptions. These are typically caused by defects in your program’s code.

þ Examples of unchecked exceptions include : ArrayIndexOutOfBoundsExceptions,ArithmeticExceptions, ...

þ Classes that inherit directly or indirectly from classError are unchecked, because Errors aresuch serious problems that your program should not even attempt to deal with them.

þ Unlike checked exceptions, the Java compiler does not examine the code to determinewhether an unchecked exception is caught or declared. Unchecked exceptions typically can beprevented by proper coding.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 34/56

Checked vs. Unchecked Exceptions (2/2)

Unchecked Exceptions

þ All exception types that are direct or indirect subclasses of RuntimeException are uncheckedexceptions. These are typically caused by defects in your program’s code.

þ Examples of unchecked exceptions include : ArrayIndexOutOfBoundsExceptions,ArithmeticExceptions, ...

þ Classes that inherit directly or indirectly from classError are unchecked, because Errors aresuch serious problems that your program should not even attempt to deal with them.

þ Unlike checked exceptions, the Java compiler does not examine the code to determinewhether an unchecked exception is caught or declared. Unchecked exceptions typically can beprevented by proper coding.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 34/56

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

public class UsingExceptions{public static void main(String[] args){try{method1();

}catch (Exception exception){System.err.printf("%s%n%n", exception.getMessage());exception.printStackTrace();

}}public static void method1() throws Exception{method2();

}public static void method2() throws Exception{method3();

}public static void method3() throws Exception{throw new Exception("Exception thrown in method3");

}}

Exception thrown in method3

java.lang.Exception: Exception thrown in method3at UsingExceptions.method3(UsingExceptions.java:38)at UsingExceptions.method2(UsingExceptions.java:33)at UsingExceptions.method1(UsingExceptions.java:29)at UsingExceptions.main(UsingExceptions.java:7)

public class UsingExceptions{public static void main(String[] args){try{method1();

}catch (Exception exception){System.err.printf("%s%n%n", exception.getMessage());exception.printStackTrace();

}}public static void method1() throws Exception{method2();

}public static void method2() throws Exception{method3();

}public static void method3() throws Exception{throw new Exception("Exception thrown in method3");

}}

Exception thrown in method3

java.lang.Exception: Exception thrown in method3at UsingExceptions.method3(UsingExceptions.java:38)at UsingExceptions.method2(UsingExceptions.java:33)at UsingExceptions.method1(UsingExceptions.java:29)at UsingExceptions.main(UsingExceptions.java:7)

public class UsingExceptions{public static void main(String[] args){try{method1();

}catch (Exception exception){System.err.printf("%s%n%n", exception.getMessage());

StackTraceElement[] traceElements = exception.getStackTrace();System.out.printf("%nStack trace from getStackTrace:%n");System.out.println("Class\t\tFile\t\t\tLine\tMethod");

for (StackTraceElement element : traceElements){System.out.printf("%s\t", element.getClassName() );System.out.printf("%s\t", element.getFileName() );System.out.printf("%s\t", element.getLineNumber() );System.out.printf("%s%n", element.getMethodName() );

}}

}public static void method1() throws Exception{method2();

}public static void method2() throws Exception{method3();

}public static void method3() throws Exception{throw new Exception("Exception thrown in method3");

}}

Exception thrown in method3

Stack trace from getStackTrace:Class File Line MethodUsingExceptions UsingExceptions.java 38 method3UsingExceptions UsingExceptions.java 33 method2UsingExceptions UsingExceptions.java 29 method1UsingExceptions UsingExceptions.java 7 main

Obtaining data from an exception object

þ All exceptions derive from class Throwable, which has a printStackTrace method that outputsto the standard error stream the stack trace.

þ Class Throwable also provides a getStackTrace method that retrieves the stack-traceinformation that might be printed by printStackTrace.

þMethod getStackTrace enables custom processing of the exception information (it retrievesthe stack-trace information as an array StackTraceElement objects).

þ Each StackTraceElement provides four methods (getClassName, getFileName, getLineNumberand getMethodName) to get the class name, filename, line number and method name,respectively, for that StackTraceElement.

þ Class Throwable’s getMessage method returns the descriptive string stored in an exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 39/56

Obtaining data from an exception object

þ All exceptions derive from class Throwable, which has a printStackTrace method that outputsto the standard error stream the stack trace.

þ Class Throwable also provides a getStackTrace method that retrieves the stack-traceinformation that might be printed by printStackTrace.

þMethod getStackTrace enables custom processing of the exception information (it retrievesthe stack-trace information as an array StackTraceElement objects).

þ Each StackTraceElement provides four methods (getClassName, getFileName, getLineNumberand getMethodName) to get the class name, filename, line number and method name,respectively, for that StackTraceElement.

þ Class Throwable’s getMessage method returns the descriptive string stored in an exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 39/56

Obtaining data from an exception object

þ All exceptions derive from class Throwable, which has a printStackTrace method that outputsto the standard error stream the stack trace.

þ Class Throwable also provides a getStackTrace method that retrieves the stack-traceinformation that might be printed by printStackTrace.

þMethod getStackTrace enables custom processing of the exception information (it retrievesthe stack-trace information as an array StackTraceElement objects).

þ Each StackTraceElement provides four methods (getClassName, getFileName, getLineNumberand getMethodName) to get the class name, filename, line number and method name,respectively, for that StackTraceElement.

þ Class Throwable’s getMessage method returns the descriptive string stored in an exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 39/56

Obtaining data from an exception object

þ All exceptions derive from class Throwable, which has a printStackTrace method that outputsto the standard error stream the stack trace.

þ Class Throwable also provides a getStackTrace method that retrieves the stack-traceinformation that might be printed by printStackTrace.

þMethod getStackTrace enables custom processing of the exception information (it retrievesthe stack-trace information as an array StackTraceElement objects).

þ Each StackTraceElement provides four methods (getClassName, getFileName, getLineNumberand getMethodName) to get the class name, filename, line number and method name,respectively, for that StackTraceElement.

þ Class Throwable’s getMessage method returns the descriptive string stored in an exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 39/56

Obtaining data from an exception object

þ All exceptions derive from class Throwable, which has a printStackTrace method that outputsto the standard error stream the stack trace.

þ Class Throwable also provides a getStackTrace method that retrieves the stack-traceinformation that might be printed by printStackTrace.

þMethod getStackTrace enables custom processing of the exception information (it retrievesthe stack-trace information as an array StackTraceElement objects).

þ Each StackTraceElement provides four methods (getClassName, getFileName, getLineNumberand getMethodName) to get the class name, filename, line number and method name,respectively, for that StackTraceElement.

þ Class Throwable’s getMessage method returns the descriptive string stored in an exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 39/56

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

public class UsingChainedExceptions{

public static void main(String[] args){try{method1();

}catch (Exception exception){exception.printStackTrace();

}}public static void method1() throws Exception{try{method2();

}catch (Exception exception){throw new Exception("Exception thrown in method1", exception);

}}public static void method2() throws Exception{try{method3();

}catch (Exception exception){throw new Exception("Exception thrown in method2", exception);

}}public static void method3() throws Exception{throw new Exception("Exception thrown in method3");

}}

java.lang.Exception: Exception thrown in method1at UsingChainedExceptions.method1(UsingChainedExceptions.java:22)at UsingChainedExceptions.main(UsingChainedExceptions.java:7)

Caused by: java.lang.Exception: Exception thrown in method2at UsingChainedExceptions.method2(UsingChainedExceptions.java:33)at UsingChainedExceptions.method1(UsingChainedExceptions.java:28)... 1 more

Caused by: java.lang.Exception: Exception thrown in method3at UsingChainedExceptions.method3(UsingChainedExceptions.java:38)at UsingChainedExceptions.method2(UsingChainedExceptions.java:29)... 2 more

Chained Exceptions

þ Sometimes a method responds to an exception by throwing a different exception type that’sspecific to the current application.

þ If a catch block throws a new exception, the original exception’s information and stack traceare lost.

þ Chained exceptions enable an exception object to maintain the complete stack-traceinformation from the original exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 43/56

Chained Exceptions

þ Sometimes a method responds to an exception by throwing a different exception type that’sspecific to the current application.

þ If a catch block throws a new exception, the original exception’s information and stack traceare lost.

þ Chained exceptions enable an exception object to maintain the complete stack-traceinformation from the original exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 43/56

Chained Exceptions

þ Sometimes a method responds to an exception by throwing a different exception type that’sspecific to the current application.

þ If a catch block throws a new exception, the original exception’s information and stack traceare lost.

þ Chained exceptions enable an exception object to maintain the complete stack-traceinformation from the original exception.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 43/56

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

A New Exception Type Must Extend an Existing One

þ A new exception class must extend an existing exception class to ensure that the class can beused with the exception-handling mechanism.

þ An exception class is like any other class ; however, a typical new exception class contains onlyfour constructors :

1 one that takes no arguments and passes a default error message String to the superclassconstructor,

2 one that receives a customized error message as a String and passes it to the superclassconstructor,

3 one that receives a customized error message as a String and a Throwable (for chainingexceptions) and passes both to the superclass constructor,

4 one that receives a Throwable (for chaining exceptions) and passes it to the superclassconstructor.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 45/56

A New Exception Type Must Extend an Existing One

þ A new exception class must extend an existing exception class to ensure that the class can beused with the exception-handling mechanism.

þ An exception class is like any other class ; however, a typical new exception class contains onlyfour constructors :

1 one that takes no arguments and passes a default error message String to the superclassconstructor,

2 one that receives a customized error message as a String and passes it to the superclassconstructor,

3 one that receives a customized error message as a String and a Throwable (for chainingexceptions) and passes both to the superclass constructor,

4 one that receives a Throwable (for chaining exceptions) and passes it to the superclassconstructor.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 45/56

A New Exception Type Must Extend an Existing One

þ A new exception class must extend an existing exception class to ensure that the class can beused with the exception-handling mechanism.

þ An exception class is like any other class ; however, a typical new exception class contains onlyfour constructors :

1 one that takes no arguments and passes a default error message String to the superclassconstructor,

2 one that receives a customized error message as a String and passes it to the superclassconstructor,

3 one that receives a customized error message as a String and a Throwable (for chainingexceptions) and passes both to the superclass constructor,

4 one that receives a Throwable (for chaining exceptions) and passes it to the superclassconstructor.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 45/56

A New Exception Type Must Extend an Existing One

þ A new exception class must extend an existing exception class to ensure that the class can beused with the exception-handling mechanism.

þ An exception class is like any other class ; however, a typical new exception class contains onlyfour constructors :

1 one that takes no arguments and passes a default error message String to the superclassconstructor,

2 one that receives a customized error message as a String and passes it to the superclassconstructor,

3 one that receives a customized error message as a String and a Throwable (for chainingexceptions) and passes both to the superclass constructor,

4 one that receives a Throwable (for chaining exceptions) and passes it to the superclassconstructor.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 45/56

A New Exception Type Must Extend an Existing One

þ A new exception class must extend an existing exception class to ensure that the class can beused with the exception-handling mechanism.

þ An exception class is like any other class ; however, a typical new exception class contains onlyfour constructors :

1 one that takes no arguments and passes a default error message String to the superclassconstructor,

2 one that receives a customized error message as a String and passes it to the superclassconstructor,

3 one that receives a customized error message as a String and a Throwable (for chainingexceptions) and passes both to the superclass constructor,

4 one that receives a Throwable (for chaining exceptions) and passes it to the superclassconstructor.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 45/56

A New Exception Type Must Extend an Existing One

þ A new exception class must extend an existing exception class to ensure that the class can beused with the exception-handling mechanism.

þ An exception class is like any other class ; however, a typical new exception class contains onlyfour constructors :

1 one that takes no arguments and passes a default error message String to the superclassconstructor,

2 one that receives a customized error message as a String and passes it to the superclassconstructor,

3 one that receives a customized error message as a String and a Throwable (for chainingexceptions) and passes both to the superclass constructor,

4 one that receives a Throwable (for chaining exceptions) and passes it to the superclassconstructor.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 45/56

public class NegValueException extends Exception{

public NegValueException(double val, String msg){super("[val=" + val + "] " + msg);

}}

public class Circle {private Point center ;private double radius ;

public Circle(Point center, double radius) throws NegValueException{if(radius < 0)throw (new NegValueException(radius,"positive value expected for radius"));

this.center = center;this.radius = radius;

}}

public class NegValueException extends Exception{

public NegValueException(double val, String msg){super("[val=" + val + "] " + msg);

}}

public class Circle {private Point center ;private double radius ;

public Circle(Point center, double radius) throws NegValueException{if(radius < 0)throw (new NegValueException(radius,"positive value expected for radius"));

this.center = center;this.radius = radius;

}}

public class TestingCircleCreation{

public static void main(String[] args){try{new Circle(new Point(1,1),-5);

}catch(NegValueException e){e.printStackTrace();

}}

}

NegValueException: [val=-5.0] positive value expected for radiusat Circle.<init>(Circle.java:9)at TestingCircleCreation.main(TestingCircleCreation.java:7)

public class TestingCircleCreation{

public static void main(String[] args){try{new Circle(new Point(1,1),-5);

}catch(NegValueException e){e.printStackTrace();

}}

}

NegValueException: [val=-5.0] positive value expected for radiusat Circle.<init>(Circle.java:9)at TestingCircleCreation.main(TestingCircleCreation.java:7)

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

Assertions

þWhen implementing and debugging a class, it’s sometimes useful to state conditions thatshould be true at a particular point in a method.

þ These conditions, called assertions, help ensure a program’s validity by catching potential bugsand identifying possible logic errors during development.

þ Preconditions and postconditions are two types of assertions :Preconditions are assertions about a program’s state when a method is invoked,postconditions are assertions about its state after a method finishes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 49/56

Assertions

þWhen implementing and debugging a class, it’s sometimes useful to state conditions thatshould be true at a particular point in a method.

þ These conditions, called assertions, help ensure a program’s validity by catching potential bugsand identifying possible logic errors during development.

þ Preconditions and postconditions are two types of assertions :Preconditions are assertions about a program’s state when a method is invoked,postconditions are assertions about its state after a method finishes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 49/56

Assertions

þWhen implementing and debugging a class, it’s sometimes useful to state conditions thatshould be true at a particular point in a method.

þ These conditions, called assertions, help ensure a program’s validity by catching potential bugsand identifying possible logic errors during development.

þ Preconditions and postconditions are two types of assertions :Preconditions are assertions about a program’s state when a method is invoked,postconditions are assertions about its state after a method finishes.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 49/56

Java assertions

þ Java includes two versions of the assert statement for validating assertions programatically :

assert expression ;

which throws an AssertionError (a subclass of Error) if expression is false .

assert expression1 : expression2 ;

which evaluates expression1 and throws an AssertionError with expression2 as the error messageif expression1 is false .

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 50/56

Java assertions

þ Java includes two versions of the assert statement for validating assertions programatically :

assert expression ;

which throws an AssertionError (a subclass of Error) if expression is false .

assert expression1 : expression2 ;

which evaluates expression1 and throws an AssertionError with expression2 as the error messageif expression1 is false .

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 50/56

Java assertions

þ Java includes two versions of the assert statement for validating assertions programatically :

assert expression ;

which throws an AssertionError (a subclass of Error) if expression is false .

assert expression1 : expression2 ;

which evaluates expression1 and throws an AssertionError with expression2 as the error messageif expression1 is false .

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 50/56

import java.util.Scanner;

public class AssertTest{

public static void main(String[] args){Scanner input = new Scanner(System.in);System.out.print("Enter a number between 0 and 10: ");int number = input.nextInt();

assert (number >= 0 && number <= 10) : "bad number: " + number;System.out.printf("You entered %d%n", number);

}}

$java -ea AssertTestEnter a number between 0 and 10: 5You entered 5

$java -ea AssertTestEnter a number between 0 and 10: 50Exception in thread "main" java.lang.AssertionError: bad number: 50at AssertTest.main(AssertTest.java:11)

import java.util.Scanner;

public class AssertTest{

public static void main(String[] args){Scanner input = new Scanner(System.in);System.out.print("Enter a number between 0 and 10: ");int number = input.nextInt();

assert (number >= 0 && number <= 10) : "bad number: " + number;System.out.printf("You entered %d%n", number);

}}

$java -ea AssertTestEnter a number between 0 and 10: 5You entered 5

$java -ea AssertTestEnter a number between 0 and 10: 50Exception in thread "main" java.lang.AssertionError: bad number: 50at AssertTest.main(AssertTest.java:11)

import java.util.Scanner;

public class AssertTest{

public static void main(String[] args){Scanner input = new Scanner(System.in);System.out.print("Enter a number between 0 and 10: ");int number = input.nextInt();

assert (number >= 0 && number <= 10) : "bad number: " + number;System.out.printf("You entered %d%n", number);

}}

$java -ea AssertTestEnter a number between 0 and 10: 5You entered 5

$java -ea AssertTestEnter a number between 0 and 10: 50Exception in thread "main" java.lang.AssertionError: bad number: 50at AssertTest.main(AssertTest.java:11)

1 Exception Handling

2 Finally Block

3 Java Exception Hierarchy

4 Exception Object

5 Chained Exceptions

6 Declaring New Exception Types

7 Assertions

8 Try with Resources

Automatic Resource Deallocation (1/2)

Remark

Typically resource-release code should be placed in a finally block to ensure that a resource isreleased, regardless of whether there were exceptions when the resource was used in the cor-responding try block.

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 53/56

import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;

public class TryWithResourcesExample {

public static void main(String[] args) {BufferedReader reader;try{reader = new BufferedReader(new FileReader("fichier.txt"))String line = reader.readLine();while (line != null) {System.out.println(line);line = reader.readLine();

}}catch (FileNotFoundException e) {e.printStackTrace();

}catch (IOException e) {e.printStackTrace();

}finally{reader.close();

}}

}

Automatic Resource Deallocation (2/2)

try(ClassName theObject = new ClassName()){// use theObject here

}catch (ExceptionType e){// catch exceptions that occur while using the resource

}

þ An alternative notation the try-with-resources statement simplifies writing code in which youobtain one or more resources, use them in a try block and release them in a corresponding finallyblock.

þ Each resource must be an object of a class that implements the AutoCloseable interface, andthus provides a close method.

þ You can allocate multiple resources in the parentheses following try by separating them with asemicolon ( ; )

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 55/56

Automatic Resource Deallocation (2/2)

try(ClassName theObject = new ClassName()){// use theObject here

}catch (ExceptionType e){// catch exceptions that occur while using the resource

}

þ An alternative notation the try-with-resources statement simplifies writing code in which youobtain one or more resources, use them in a try block and release them in a corresponding finallyblock.

þ Each resource must be an object of a class that implements the AutoCloseable interface, andthus provides a close method.

þ You can allocate multiple resources in the parentheses following try by separating them with asemicolon ( ; )

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 55/56

Automatic Resource Deallocation (2/2)

try(ClassName theObject = new ClassName()){// use theObject here

}catch (ExceptionType e){// catch exceptions that occur while using the resource

}

þ An alternative notation the try-with-resources statement simplifies writing code in which youobtain one or more resources, use them in a try block and release them in a corresponding finallyblock.

þ Each resource must be an object of a class that implements the AutoCloseable interface, andthus provides a close method.

þ You can allocate multiple resources in the parentheses following try by separating them with asemicolon ( ; )

[email protected] | CPOO : Gestion des Exceptions en Java | 2A DUT Informatique - IUT d’Orsay | 11 Octobre 2019 55/56

import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;

public class TryWithResourcesExample {

public static void main(String[] args) {try (BufferedReader reader = new BufferedReader(new FileReader("fichier.txt"))) {String line = reader.readLine();while (line != null) {System.out.println(line);line = reader.readLine();

}}catch (FileNotFoundException e) {e.printStackTrace();

}catch (IOException e) {e.printStackTrace();

}}

}