Vous êtes sur la page 1sur 34

Exceptions Handling

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Syntax Errors, Runtime Errors, and Logic
Errors
You learned that 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 doesn't
perform the way it was intended to.
2

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Runtime Errors

1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catch Runtime Errors
1 import java.util.*; Run
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 4 } while (continueInput);
25 }
13 }
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exception Classes
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

5 Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
System Errors

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

System errors are thrown by JVM Several more classes


LinkageError
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely VirtualMachineError

occur. If one does, there is little Error


you can do beyond notifying the AWTError
user and trying to terminate the
program gracefully. Several more classes
6

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exceptions
Exception describes errors ClassNotFoundException
caused by your program
and external IOException
circumstances. These ArithmeticException
errors can be caught and Exception AWTException
handled by your program. NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

7 Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Runtime Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError RuntimeException is caused by


Error programming errors, such as bad
casting, accessing an out-of-bounds
AWTError
array, and numeric errors.

Several more classes


8

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked Exceptions vs. Unchecked
Exceptions
• Exceptions which are checked for during compile time are
called checked exceptions.
Example: SQLException or any userdefined exception
extending the Exception class
• Exceptions which are not checked for during compile time
are called unchecked exception.
Example: NullPointerException or any class extending the
RuntimeException class.
• All the checked exceptions must be handled in the program.
• The exceptions raised, if not handled will be handled by the
Java Virtual Machine. The Virtual machine will print the stack
trace of the exception indicating the stack of exception and
the line where it was caused.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked or Unchecked Exceptions

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error Unchecked
exception.
AWTError

1 Several more classes


0

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring, Throwing, and Catching
Exceptions

method1() { declare exception


method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}

1
1

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as declaring
exceptions.

public void myMethod()


throws IOException

public void myMethod()


throws IOException, OtherException

1
2

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
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;

1
3

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Throwing Exceptions Example

/** Set a new radius */


public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}

1
4

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}

1
5

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catching Exceptions
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }

1
6

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}

1
7

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

1
8

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
1
9

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution

The final block is


try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
2
0

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution

Next statement in the


try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
2
1

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
2
2

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
2
3

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
2
4

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
2
5

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try {
statement1;
statement2 throws an
statement2;
exception of type
statement3;
}
Exception2.
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
2
6

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
2
7

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
2
8

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Trace a Program Execution
try {
statement1;
Rethrow the exception
statement2;
and control is
statement3;
}
transferred to the caller
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
2
9

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
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.

3
0

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
When to Throw Exceptions
• An exception occurs in a method. If you want the
exception to be processed by its caller, you should
create an exception object and throw it. If you can
handle the exception in the method where it occurs,
there is no need to throw it.

3
1

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
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");
3

} 2

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
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");

3
3

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
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.

3
4

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6

Vous aimerez peut-être aussi