Anda di halaman 1dari 30

Chapter 5

Exceptions

Suzana/Java II-Chapt2

4th Ed Chapter N - 1

Objectives

Define exceptions
Use try, catch and finally
Describe exception categories
Identify common exceptions

Suzana/Java II-Chapt2

4th Ed Chapter N - 2

Exceptions

What is an exception ? An event that is raised by Java during the running of a program
and disrupt the normal flow of the program execution.

What causes Java to raise it? Runtime errors (bugs)

Reasons for runtime errors to occur? Many reasons..


Eg : Not handling certain input correctly, Opening file which is not exist, Accessing out-ofbounds array element, Dividing by zero, Referencing missing files, Calling invalid
functions/methods, Etc.

Conclusion ? When a runtime error occurs, Java raises exception (event)

What is the problem if the exception is NOT handled? A program may terminate
abnormally . Eg: Program unexpectedly quits while running .. and you might not see the
desired output.. and also you do not know what is happening !! )

What is the solution? Java provides programmers with the capability to elegantly handle
those runtime errors. It is referred to exception handling

Suzana/Java II-Chapt2

4th Ed Chapter N - 3

Code with no exception handling


Scenario : User input double value unintentionally..

If an exception occurs on Line 8, the rest of the lines in the


method are skipped and the program is terminated abnormally !!
Reason for runtime error for this scenario: Invalid input by
user, a double value is entered (instead of integer ! )
program terminated !
Suzana/Java II-Chapt2

4th Ed Chapter N - 4

Code with no exception handling

An exception occurs when you enter an invalid input


Suzana/Java II-Chapt2

4th Ed Chapter N - 5

Code with exception handling


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

try
{

System.out.println( Enter an integer);


int number = in.nextInt();
System.out.println( The number entered is + number);

catch
{
}

(Exception ex)
System.out.println(Incorrect output: an integer is required);

System.out.println( Execution continues );


}
}

X : If exception occur on this line (input), the rest of the line in the try clause are skipped.
Control is now transferred to the catch clause
Y: After the exception is caught and processed, the control is transferred to the next
statement after the try-catch block
Suzana/Java II-Chapt2

4th Ed Chapter N - 6

Checked and Unchecked Exceptions


Java provides 2 broad categories of exceptions :
Checked exceptions
Unchecked exceptions

Suzana/Java II-Chapt2

4th Ed Chapter N - 7

Exception and Error Class


The Exception class is the superclass that
represent checked exceptions. Checked exceptions can
be caught and handled by your program. It is originated
mostly from programming errors in your code.

The Error class is the superclass that represent


unchecked exceptions. It is used for the unchecked
serious error conditions from which your program
is not expected to attempt recovery

Suzana/Java II-Chapt2

4th Ed Chapter N - 8

Java predefined exception classes

Suzana/Java II-Chapt2

4th Ed Chapter N - 9

Example of code with runtime exception


This code is intended to demonstrate a runtime
exceptions
1. public class Course
2. {
public static void main(String[] args)
3.
{ int i = 0;
4.
String subject[ ] = {Java,Network,Maths};
5.
while (i < 4)
6.
{
System.out.println(subject[i]);
7.
i++;
8.
}
9.
}
10. }
any logic

error ?

Suzana/Java II-Chapt2

4th Ed Chapter N

- 10

Code with runtime exception (cont)


If that exception is thrown and no action is taken to handle
the situation, the program will terminate with the error
message
This is the behavior of the program previously shown to
you when the loop has executed 4 timesThe error
message is :
output
error message
Java
Network
Maths
java.lang.ArrayIndexOutOfBoundsException:atCourse.main
(Course.java:12)

Suzana/Java II-Chapt2

4th Ed Chapter N

- 11

* Exception Handling( in method chaining)


Java provides a mechanism for figuring out which
exception was thrown and how to recover from it
Exception handling allows a program to catch
exceptions, handle them and then continue
program execution
Java s exception handling is based on 3
operations :
declare an exception
throwing an exception
catching an exception
Suzana/Java II-Chapt2

4th Ed Chapter N

- 12

An exception occurs in a method.


If you want the exception to be handled by its
caller, you should create an exception object and
throw it.
If you can handle the exception in the method
where the exception occurs, there is no need to
throw exception object.

Suzana/Java II-Chapt2

4th Ed Chapter N

- 13

* Exception Handling (in method chaining)


declare exception
method1( )

method2( )

{
try
{ invoke method2;
}
catch (Exception ex )
{ process exception;
}

throws Exception

if (an error occurs)


{

throw new Exception();

}
}

catch exception

Suzana/Java II-Chapt2

throw exception

4th Ed Chapter N

- 14

* Understanding Exception Handling (in


method chaining)
Every method must state the type of the checked
exception it might throw. This is known as
(1)declaring exceptions
A method that detects an error can create an
instance of an appropriate exception type and
throw it. This is known as (2) throwing an
exception
When an exception is thrown , it can be caught
and handled in a try-catch block as follows :

Suzana/Java II-Chapt2

4th Ed Chapter N

- 15

Understanding Exception Handling (cont)


When an exception is thrown , it can be caught
and handled in a try-catch block as follows :
try
{
statements;
// statement that might throw exception
}
catch (Exception1 exVar1)
{
handler for exception1;
}
catch (Exception2 exVar2)
{
handler for exception2;
}
.....
catch (Exception3 exVar3)
{
handler for exception3;
}

Suzana/Java II-Chapt2

4th Ed Chapter N

- 16

Understanding Exception Handling (cont)


If no exceptions arise during the execution of the try
clause, the catch clauses are skipped
If one of the statements inside the try block throws an
exception, Java skips the remaining statements in the try
block and starts the process of finding the code to handle
exception
The code that handles the exception is called the exception
handler
Each catch clause is examined in turn to see whether the
type of the exception object is an instance of the exception
class in the catch clause.
Suzana/Java II-Chapt2

4th Ed Chapter N

- 17

* Understanding Exception Handling (cont)


If so, the exception object is assigned to the variable
declared and the code in the catch clause is executed
If no handler is found, Java exits this method, passes the
exception to the method that invoke the method and
continue the process to find the handler
If no handler is found in the chain of methods being
invoked, the program terminates and print an error
message on the console
The process of finding the handler is called (3) catching an
exception
Suppose the main method invokes method1, method1
invokes method2, method2 invokes method3, how would
you explain the next diagram ?
Suzana/Java II-Chapt2

4th Ed Chapter N

- 18

* Understanding Exception Handling (cont)


main method( )
{
try
{
invoke method1;
statement1;
}
catch (Exception1 ex1)
{ process ex1;
method1( )
}
{
statement2;
try
}
}
{
invoke method2;
statement3;
}
catch (Exception2 ex2)
{ process ex2;
}
statement4;
}
Suzana/Java II-Chapt2

An exception is thrown
in method3

method2( )
{
try
{
invoke method3;
statement5;
}
catch (Exception3 ex3)
{ process ex3;
}
statement6;
}
4th Ed Chapter N

- 19

Obtain information from exception objects in


catch clause
An exception object contains valuable information
about the exception. You may use the following
instance methods in the
Java.lang.Throwable class to get information
regarding exception :
public String getMessage( )

//

public String toString( )

// returns the concatenation of 3 strings

Eg:

SOP(ex); // print object


SOP(ex.toString());

return the detailed message of the


Throwable object

(1) The full name of the exception


class (2) a colon (3) the getMessage ()

public void printStackTrace( ) // prints the Throwable object and its trace
information on the console
Suzana/Java II-Chapt2

4th Ed Chapter N

- 20

Suzana/Java II-Chapt2

4th Ed Chapter N

- 21

Obtain information from exception objects in


catch clause (cont)
java.lang.Throwable

Suzana/Java II-Chapt2

4th Ed Chapter N

- 22

Finally clause
Occasionaly, you may want some code to be executed
regardless exception occurs or is caught
Java hasfinally clause to achieve this objective.
The syntax is :
try
{

statements;

}
catch(TheException ex)
{

handling ex;

}
finally
{

finalStatements;

}
Suzana/Java II-Chapt2

4th Ed Chapter N

- 23

Code
example :

Suzana/Java II-Chapt2

4th Ed Chapter N

- 24

Code
example
(cont)

Suzana/Java II-Chapt2

4th Ed Chapter N

- 25

Common Exceptions
Arithmetic exception the result of divide-by-zero
operation for integers int i = 12/0;
NullPointerException an attempt to access the data
or method of an object using a variable that is not refer to
an object Date d = null;
System.out.println(d.toString);

NegativeArraySizeException - an attempt to create


an array with a negative dimension size
ArrayIndexOutOfBoundsException an attempt to
an element of an array beyond the arrays size
SecurityException
Suzana/Java II-Chapt2

4th Ed Chapter N

- 26

Lets program.. : Exceptions


Exersise 1 (Optional)
Objective : Write a program that uses Exception class
(checked exception). In this exercise you will
use the try-catch block to handle a simple checked
exception
Instruction :
Type the program on page 4. Test your program by giving a double input
value instead of an integer value. Modify your program so that it uses
exception handling as on page 5. Give the same invalid input. See the
difference in the two results.

Suzana/Java II-Chapt2

4th Ed Chapter N

- 27

Lets program.. : Exceptions


Exersise 2
Objective : Write a program that uses RuntimeException class.
In this exercise you will use the try-catch block to handle a simple
runtime exception
Instruction :
The code in this program is poorly implemented, because the loop should test for the
exact size of the flower array. However the purpose of this exercise is to give you
hands-on experience with exceptions and how to catch them.

public class TestException


{ public static void main(String[] args)
{ String[] flower ={lily, rose, tulip};
for(int i=0; true; i++)
System.out.ptintln(flower[ + i + ] is +flower[i]);
}
}
Suzana/Java II-Chapt2

4th Ed Chapter N

- 28

Lets program.. : Exceptions (cont)


1.

Compile and run the TestExceptions program

2.

Write down the result of the test on a piece of paper

3.

Modify the TestExceptions program to handle the


ArrayIndexBoundException by wrapping the for loop in a tryblock

4.

Write the catch block that cathes that exception and prints out the
exception object. Print also a message Quitting

5.

Recompile and run the program. Compare the result with the one on the
paper just now

6.

The second result should look like this :


flower[0] is lily
flower[1] is rose
flower[3] is

tulip

Exception caught : java.lang.ArrayIndexOutOfBoundsException


Quitting
Suzana/Java II-Chapt2

4th Ed Chapter N

- 29

Lets program.. : Exceptions (cont)


Exersise 3
Objective : Write a program that uses IllegalTriangleException class.
In this exercise you will declare, throw and catch the exception to
handle it.
Instruction :
Create a Triangle class which define the three sides. In a triangle, the sum of any
two sides is greater than the other side. The Triangle class must adhere to this
rule. Create the IllegalTriangleException class, and modify the constructor of the
Triangle class to throw an IllegalTriangleException object if a triangle is created
with sides that violate the rule, as follows :
// construct a triangle with the specific sides

public Triangle (double side1, double side2, double


side3) throws IllegalTriangleException {
// implement ation
}
Suzana/Java II-Chapt2

4th Ed Chapter N

- 30

Anda mungkin juga menyukai