63
1 Exception Handling Lecture 28 Based on Slides of Dr. Norazah Yusof

Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

1

Exception Handling

Lecture 28 Based on Slides of Dr. Norazah Yusof

Page 2: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

2

Categories of Errors

There are three categories of errors:

syntax errors,

runtime errors, and

logic errors.

Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler.

Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out.

Logic errors occur when a program does not perform the way it was intended to.

Page 3: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

3

Exception

Exception is a runtime error – an event that occurs

during the execution of a program that disrupts the

normal flow of instructions.

The program that does not provide code for

catching and handling exceptions will terminate

abnormally, and may cause serious problems.

Exceptions occurs for various reasons:

User enters an invalid input.

Program attempt to open a file that doesn’t exist.

Program attempt to access an out-of-bounds

array element

and many more…

Page 4: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

4

Uncaught Exceptions

When an exception is thrown, it cannot be ignored.

It must be handled by the program, or by the default exception handler.

When the code in a method throws an exception:

normal execution of that method stops, and

the JVM searches for a compatible exception handler inside the method.

4

Page 5: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

5

Runtime Errors

import java.util.Scanner;

public class ExceptionDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");

int number = scanner.nextInt();

// Display the result

System.out.println(

"The number entered is " + number);

}

}

If an exception occurs on this

line, the rest of the lines in the

method are skipped and the

program is terminated.

Terminated.

1

2

3

4

5

6

7

8

9

10

11

12

13

Page 6: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

6

Exception – stack trace

Several information are displayed in response to

the invalid input.

This information is known as stack trace, that

include:

The name of the exception,

The method call stack

Page 7: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

7

Exception – stack trace

From the last line of the stack trace:

The exception was detected at line 8 of the main method, contains the class name and method (Example1b.main) along with the filename and and line number (Example1b.java:8)

Moving up the stack:

The exception occurred at line 2000 in the nextInt method of the Scanner class.

The exception occurred at line 2040 in the overloaded nextInt method of the Scanner class.

The exception occurred at line 1431 in the next method of the Scanner class.

The exception occurred at line 819 in the throwFor method of the Scanner class.

The last method in the call chain actually threw an InputMismatchException.

Page 8: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

8

Catch Runtime Errors

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

import java.util.*;

public class Example1b{

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

try {

System.out.println ("Enter an integer:");

int num = scanner.nextInt();

System.out.println ("The number entered is:"+

num);

}

catch (InputMismatchException ex) {

System.out.println ("Cuba Lagi ("+

"Kesalahan input: nombor integer diperlukan)");

scanner.nextLine(); //discard input

}

}

}

If an exception

occurs on this

line, the rest of

lines in the try

block are

skipped and the

control is

transferred to

the catch block.

Page 9: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

9

Exception handling

• The try-block contains the statements that

might throw exceptions.

• The catch-block handles the exceptional

case. The catch-block takes a parameter of type Exception.

• When a statement in the try-block throws

an exception, the execution in the try-block

ends and control passes to the catch-

block(s).

Page 10: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

10

Exception Classes

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

Page 11: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

11

Exception Classes

The exception classes can be classified

into three major types:

1. System errors

2. Exceptions

3. Runtime exceptions

Page 12: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

12

System Errors

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

System errors are thrown by

JVM and represented in the

Error class. The Error class

describes internal system errors.

Such errors rarely occur. If one

does, there is little you can do

beyond notifying the user and

trying to terminate the program

gracefully.

Page 13: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

13

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

Exceptions

Exception describes

errors caused by your

program and external

circumstances. These

errors can be caught and

handled by your

program.

Example:

1. Class not found

2. Clone not supported

3. Related input/output

operations

Page 14: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

14

Runtime Exceptions

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

RuntimeException is caused by

programming errors, such as bad

casting, accessing an out-of-

bounds array, and numeric errors.

This exceptions are generally

thrown by the JVM.

They are known as unchecked

exceptions.

Page 15: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

15

Checked and Unchecked Exceptions

There are two categories of exceptions:

unchecked

checked

Unchecked exceptions are those that are derived from the Error class or the

RuntimeException class.

Exceptions derived from Error are thrown

when a critical error occurs, and should not be

handled.

RuntimeException serves as a superclass for

exceptions that result from programming

errors. 15

Page 16: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

16

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

Unchecked Exceptions

Unchecked

exception.

Page 17: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

17

Unchecked Exceptions

These exceptions can be avoided with

properly written code.

With an unchecked exception, however,

compiler doesn't force client programmers

either to catch the exception or declare it

in a throws clause.

All exceptions that are not derived from Error or RuntimeException are checked

exceptions.

17

Page 18: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

18

Is any exception belonging to a subclass of RuntimeException.

It is not checked by the compiler and can occur

anywhere in the program.

In most cases, unchecked exceptions reflect

programming logic errors that are not recoverable.

For example,

a NullPointerException is thrown if you access an

object through a reference variable before an

object is assigned to it;

an ArrayIndexOutOfBoundsException is thrown if

you access an element in an array outside the

bounds of the array.

Unchecked Exceptions

Page 19: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

19

Is one that can be analyzed by the compiler

(JVM).

A checked exception is any subclass of Exception, excluding class RuntimeException

and its subclasses.

You should compulsorily handle the checked

exceptions in your code, otherwise your code

will not be compiled. i.e you should put the code

which may cause checked exception in try block.

"checked" means they will be checked at

compile time itself.

Checked Exceptions

Page 20: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

20

Checked Exceptions

There are two ways to handle checked

exceptions. You may declare the exception

using a throws clause or you may use the

try..catch block.

The most perfect example of Checked Exceptions is IOException which should be

handled in your code compulsorily or else

your code will throw a Compilation Error.

20

Page 21: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

21

Catch or Declare Checked Exceptions

Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method.

For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b).

void p1() {

try {

p2();

}

catch (IOException ex) {

...

}

}

(a)

(b)

void p1() throws IOException {

p2();

}

Page 22: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

22

Checked Exceptions

// This method will not compile!

public static void main(String args[]){

BufferedReader input = new BufferedReader

(new InputStreamReader(System.in));

String inputData;

int num;

System.out.println ("Enter an integer:");

inputData = input.readLine();

num = Integer.parseInt(inputData);

System.out.println ("The square is:" +

(num*num));

}

22

Page 23: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

23

Checked Exceptions

The code in this method is capable of throwing

checked exceptions.

Ways to solve:

Either:

The keyword throws can be written at the end of

the method header, followed by a list of the types of

exceptions that the method can throw.

public static void main(String args[]) throws

IOException {

23

Page 24: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

24

//program 11.2b

import java.io.*;

public class Example2 {

public static void main(String args[]) throws

IOException {

BufferedReader input = new BufferedReader (new

InputStreamReader(System.in));

String inputData;

int num;

System.out.println ("Enter an integer:");

inputData = input.readLine();

num = Integer.parseInt(inputData);

System.out.println ("The square is:"+(num*num));

}

}

24

Page 25: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

25

OR: //program 11.2c

import java.io.*;

public class Example3 {

public static void main(String args[]) {

try {

BufferedReader input = new BufferedReader (new

InputStreamReader(System.in));

String inputData;

int num;

System.out.println ("Enter an integer:");

inputData = input.readLine();

num = Integer.parseInt(inputData);

System.out.println ("The square is:"+(num*num));

}

catch (NumberFormatException ex) {

System.out.println ("Wrong data type");

}

catch (IOException ex){

System.out.println ("input problem");

}

}

} 25

Page 26: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

26

Exception Handler in the method where it occurs

try

{

//the code which will cause the exception

}

catch(SomeExceptionType ex)

{

//the code which will handle an object of that

//exception class

}

:://more catch blocks

catch(AnotherExceptionType ex)

{ }

finally

{//the code which will always executed}

//Statements following the structure 26

Page 27: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

27

Exception Handler in the method where it

occurs

• The normal case is handled in a try-block.

• The exceptional case is handled in a catch-block.

• The catch-block takes a parameter of type Exception.

• If an exception is thrown, execution in the try-block ends and control passes to the catch-block(s) after the try-block

27

Page 28: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

28

How try, catch{} & finally{} works

28

try

{

}

finally

{

}

catch

{

}

catch

{

}

catch

{

}

Pick best match No

Match

Execution

leaves this

method No Exception

Page 29: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

29

Self test 1 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.io.*;

public class TestException {

public static void main (String[] args) throws

IOException {

try {

method();

System.out.println("After method call");

}

catch (ArithmeticException ex ){

System.out.println("ArithmeticException");

}

catch (RuntimeException ex ){

System.out.println("RunTimeException");

}

catch (Exception ex ){

System.out.println("Exception");

}

}

static void method() throws Exception {

System.out.println(1/0);

}

}

Page 30: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

30

Self test 1

ArithmeticException

Page 31: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

31

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import java.io.*;

public class TestException {

public static void main (String[] args) throws IOException {

try {

method();

System.out.println("After method call");

}

catch (ArithmeticException ex ){

System.out.println("ArithmeticException");

}

catch (RuntimeException ex ){

System.out.println("RunTimeException");

}

catch (Exception ex ){

System.out.println("Exception");

}

}

static void method() throws Exception {

try{ String s="abc";

System.out.println(s.charAt(3));

}

catch (RuntimeException ex ){

System.out.println("RunTimeException in method()");

}

catch (Exception ex ){

System.out.println("Exception in method()");

}

}

Page 32: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

32

Self test 2

RunTimeException in method()

After method call

Page 33: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

33

Rules

A program CANNOT have more than one catch clause per exception type in the

same try statement.

If you are handling multiple exceptions in the same try statement, then you MUST

handle the more specialized exception

classes before the more general exception

classes.

The finally block is an option block that

can appear after all the catch blocks.

33

Page 34: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

ArithmeticException

Occurs when dividing an integer by zero.

Question:

Write a program that reads a denominator

value and then divide 100 with the

denominator value.

If the user enters 0 as the denominator

value, then the exception is thrown. Write

a catch block that handle this exception,

by displaying a message: “Division by

zero!”

34

Page 35: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

35

Answer

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import java.util.*;

public class TestDivide1{

public static void main(String args[]){

try {

Scanner scanner = new Scanner(System.in);

System.out.print ("Enter the denom value:");

int denom = scanner.nextInt();

System.out.println ("The value of 100/" + denom

+": "+ 100/denom);

}

catch (ArithmeticException ex) {

System.out.println ("Division by zero error!");

}

}

}

Page 36: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

InputMismatchException

Occurs when user enters a string for an

integer variable.

Question:

Modify the program that handle the

exception when user enters a string i.e “r”

as a denominator value.

Write the appropriate catch block that

handle this exception, by displaying a

message: “Wrong input data!”

36

Page 37: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

37

Answer

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.*;

public class TestDivide2{

public static void main(String args[]){

try {

Scanner scanner = new Scanner(System.in);

System.out.print ("Enter the denom value:");

int denom = scanner.nextInt();

System.out.println ("The value of 100/" + denom

+": "+ 100/denom);

}

catch (ArithmeticException ex) {

System.out.println ("Division by zero error!");

}

catch (InputMismatchException ex) {

System.out.println ("Wrong input data!");

}

}

}

Page 38: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

printStackTrace(),getStackTrace(),

getMessage()

Class Throwable offers methods such as:

1. printStackTrace() method that output the

standard error stream the stack trace.

2. getStackTrace() method that retrieves

stack trace information that might be

printed by printStackTrace.

3. getMessage() method that returns the

descriptive string stored in an exception.

38

Page 39: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

Self Test

Question:

Modify the previous program that invoke

the printStackTrace() method when any of

the exception occurs.

39

Page 40: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

40

Example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.*;

public class TestDivide2{

public static void main(String args[]){

try {

Scanner scanner = new Scanner(System.in);

System.out.print ("Enter the denom value:");

int denom = scanner.nextInt();

System.out.println ("The value of 100/" + denom

+": "+ 100/denom);

}

catch (ArithmeticException ex) {

ex.printStackTrace();

}

catch (InputMismatchException ex) {

ex.printStackTrace();

}

}

}

Page 41: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

41

Throwing Exceptions

When the program detects an error, the program can create an instance of an appropriate exception type and throw it.

This is known as throwing an exception. Here is an example,

throw new TheException();

TheException ex = new TheException();

throw ex;

Note: keyword throws (throw) to declare (throw) an exception

Page 42: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

Write own exception

Question:

Modify the program that throw a new

exception object named

NumberFormatException with “Not

positive denom” as its parameter value.

This exception occurs when user enters a

negative value for denominator. Write the

appropriate catch block that handle this

exception, by displaying its message.

42

Page 43: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

43

Answer

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import java.util.*;

public class TestDivide4{

public static void main(String args[]){

try {

Scanner scanner = new Scanner(System.in);

System.out.print ("Enter the denom value:");

int denom = scanner.nextInt();

if (denom<0)

throw new NumberFormatException("Not a positive denom!!");

System.out.println ("The value of 100/" + denom +": "+

100/denom);

}

catch (ArithmeticException ex) {

System.out.println ("Division by zero error!");

}

catch (InputMismatchException ex) {

System.out.println ("Wrong input data!");

}

catch (NumberFormatException ex) {

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

}

}

}

}

Page 44: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

Propagate the Exception Handler

in different methods If one of the statement inside the try block

throws an exception, JVM starts the

process of finding the code to handle the

exception.

The code that handles the exception is

called the exception handler,

It is found by propagating the exception

backward through a chain of method calls,

starting from the current method.

44

Page 45: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

Propagate the Exception Handler

in different methods Each catch block is examine in turn, from

first to last, to determine whether the type

of exception is an instance of exception

class.

If so, the exception object is assigned to

the variable declared and the code in catch

block is executed.

If not, Java exit this method and passes the

execution to the method that invoked the

method, and continue the same process to

find a handler. 45

Page 46: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

Uncaught Exceptions in a method

If there is no exception handler inside the

method:

control of the program is passed to the previous

method in the call stack.

If that method has no exception handler, then control is

passed again, up the call stack, to the previous

method.

If control reaches the main method:

the main method must either handle the exception, or

the program is halted and the default exception handler

handles the exception. 46

Page 47: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

47

Propagate the Exception Handler

in different methods

main method {

...

try {

...

invoke method1;

statement1;

}

catch (Exception1 ex1) {

Process ex1;

}

statement2;

}

method1 {

...

try {

...

invoke method2;

statement3;

}

catch (Exception2 ex2) {

Process ex2;

}

statement4;

}

method2 {

...

try {

...

invoke method3;

statement5;

}

catch (Exception3 ex3) {

Process ex3;

}

statement6;

}

An exception

is thrown in

method3

Suppose the main method invoke method1, method1 invokes method2,

method2 invoke method3, and an exception occurs in method3.

Page 48: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

48

Propagate the Exception Handler

in different methods

main method {

...

try {

...

invoke method1;

statement1;

}

catch (Exception1 ex1) {

Process ex1;

}

statement2;

}

method1 {

...

try {

...

invoke method2;

statement3;

}

catch (Exception2 ex2) {

Process ex2;

}

statement4;

}

method2 {

...

try {

...

invoke method3;

statement5;

}

catch (Exception3 ex3) {

Process ex3;

}

statement6;

}

An exception

is thrown in

method3

Suppose the main method invoke method1, method1 invokes method2,

method2 invoke method3, and an exception occurs in method3.

If methof3 cannot handle the exception, method3 is aborted and

the control is returned to method2.

If the exception type is Exception3, it is caught by the catch block

for handling exception ex3 in method2. statement5 is skipped,

and statement6 is executed.

Page 49: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

49

Propagate the Exception Handler

in different methods

main method {

...

try {

...

invoke method1;

statement1;

}

catch (Exception1 ex1) {

Process ex1;

}

statement2;

}

method1 {

...

try {

...

invoke method2;

statement3;

}

catch (Exception2 ex2) {

Process ex2;

}

statement4;

}

method2 {

...

try {

...

invoke method3;

statement5;

}

catch (Exception3 ex3) {

Process ex3;

}

statement6;

}

An exception

is thrown in

method3

Suppose the main method invoke method1, method1 invokes method2,

method2 invoke method3, and an exception occurs in method3.

If the exception type is Exception2, method2 is aborted, the

control is returned to method1, and the exception is caught by

the catch block for handling exception ex2 in method1.

statement3 is skipped, and statement4 is executed.

Page 50: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

50

Propagate the Exception Handler

in different methods

main method {

...

try {

...

invoke method1;

statement1;

}

catch (Exception1 ex1) {

Process ex1;

}

statement2;

}

method1 {

...

try {

...

invoke method2;

statement3;

}

catch (Exception2 ex2) {

Process ex2;

}

statement4;

}

method2 {

...

try {

...

invoke method3;

statement5;

}

catch (Exception3 ex3) {

Process ex3;

}

statement6;

}

An exception

is thrown in

method3

Suppose the main method invoke method1, method1 invokes method2,

method2 invoke method3, and an exception occurs in method3.

If the exception type is Exception1, method1 is aborted, the control

is returned to main method, and the exception is caught by the

catch block for handling exception ex1 in main method. statement1

is skipped, and statement2 is executed.

Page 51: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

51

Propagate the Exception Handler

in different methods

main method {

...

try {

...

invoke method1;

statement1;

}

catch (Exception1 ex1) {

Process ex1;

}

statement2;

}

method1 {

...

try {

...

invoke method2;

statement3;

}

catch (Exception2 ex2) {

Process ex2;

}

statement4;

}

method2 {

...

try {

...

invoke method3;

statement5;

}

catch (Exception3 ex3) {

Process ex3;

}

statement6;

}

An exception

is thrown in

method3

Suppose the main method invoke method1, method1 invokes method2,

method2 invoke method3, and an exception occurs in method3.

If the exception type is not Exception1, Exception2, or Exception3,

the exception is not caught and the program terminates.

Statement1 and statement2 are not executed.

Page 52: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

52

Propagate the Exception Handler in different method

public class Pd

{ public void metod1(int i, int j)

{ try

{metod2(i,j); }

catch(ArithmeticException e)

{ System.out.println("i=" +i+ "\tj=" +j);

e.printStackTrace();

System.out.println("This is your problem:" +e.getMessage());

}}

public void metod2(int i, int j) throws ArithmeticException

{ System.out.println("metod2 bermula");

j = i/j;

System.out.println("metod2 berakhir");}

public static void main (String[] a)

{ Pd p = new Pd();

p.metod1(1,1); // tiada exception yang berlaku

p.metod1(1,0); // exception berlaku di metod2 }}

Page 53: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

53

Order of the Exception Handling

The order of which exceptions are specified in

catch clauses is important.

Compilation error will result if a catch clause for a

superclass type appears before a catch clause for

a subclass type.

For example:

Page 54: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

54

Wrong Order of the Exception Handling

try{

. . .

}

catch (Exception ex){

}

catch (RunTimeException ex){

}

RunTimeException class is a subclass of Exception. Error occurs because

superclass appears before a catch clause for the subclass type.

Page 55: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

55

Correct Order of the Exception Handling

try{

. . .

}

catch (RunTimeException ex){

}

catch (Exception ex){

}

RunTimeException class is a subclass of Exception.

Page 56: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

56

Cautions When Using Exceptions

Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify.

Be aware, however, that exception handling usually requires more time and resources because it requires

instantiating a new exception object,

rolling back the call stack, and

propagating the errors to the calling methods.

Page 57: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

57

When to Use Exceptions

When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code

try {

System.out.println(refVar.toString());

}

catch (NullPointerException ex) {

System.out.println("refVar is null");

}

Page 58: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

58

When to Use Exceptions

is better to be replaced by

if (refVar != null)

System.out.println(refVar.toString());

else

System.out.println("refVar is null");

Page 59: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

59

Creating Custom Exception Classes

Use the exception classes in the API whenever

possible.

Create custom exception classes if the predefined

classes are not sufficient.

Declare custom exception classes by extending

Exception or a subclass of Exception.

Page 60: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

60

Creating your own Exception class

Steps:

a) Define the Exception class as a subclass to the

Exception class:

public class MyException extends Exception

b) Build a constructor

public MyException(int i)

{

value = i;

}

c) Override a super class method public String getMessage()

{

return message;

}

d) Steps a)+ b) + c)

Page 61: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

61

Overall Picture

MyException

Exception

Page 62: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

62

public class MyException extends Exception {

private int value;

private String message;

public MyException(int i) {

value = i;

message = new String("MyException occurs at

value: " + value);

}

public String getMessage() {

return message;

}

}

Page 63: Exception Handling - Universiti Teknologi MalaysiaException handling •The try-block contains the statements that might throw exceptions. •The catch-block handles the exceptional

63

How to use the user-defined exceptions?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import java.util.*;

public class TestMyException {

public static void main(String[] args) {

Scanner inp = new Scanner(System.in);

try {

System.out.print ("Enter a value:");

int i = inp.nextInt();

if(i == -999)

throw new MyException(i);

else if (i == 123)

throw new MyException(i);

else

System.out.println ("The valid value is "+i);

}

catch (MyException ex) {

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

}

}

}