2. Introduction
Programming errors are unavoidable, even for
experienced programmers. Have three categories of errors:
syntax errors, runtime errors, and logic errors
Syntax errors arise because the rules of the language have
not been followed 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 the program doesn’t perform
the way it is intended to
3. Exception handling
Exception handling deals with runtime errors.
Runtime errors cause exceptions: events that occur
during the execution of a program and disrupts the
normal flow of control.
A program that does not provide code to handle
exceptions may terminate abnormally, causing serious
problem
4. The Basics of Java Exception Handling
Exception handling
Method detects error which it cannot deal with
Throws an exception
Exception handler
Code to catch exception and handle it
Exception only caught if handler exists
If exception not caught, block terminates
5. The Basics of Java Exception Handling
Format
Enclose code that may have an error in try
block
Follow with one or more catch blocks
Each catch block has an exception handler
If exception occurs and matches parameter in
catch block
Code in catch block executed try{
If no exception thrown code that may throw
exceptions
Exception handling code skipped }
Control resumes after catch blocks catch (ExceptionType ref)
{
exception handling
code
}
6. The Basics of Java Exception Handling
Termination model of exception handling
throw point
Place where exception occurred
Control cannot return to throw point
Block which threw exception expires
Possible to give information to exception handler
7. Javaprovides programmers with the capability to handle runtime errors.
With this capability, referred to as exception handling, so you can develop
robust programs for mission-critical computing.
The following program terminates abnormally because the divisor is 0, which
causes a numerical error. Note there is no code to explicitly to explicitly
handle the exception
public class Test
{
public static void main(String [] args)
{
System.out.println(3/0); // Throws ArithmeticException
}
}
8. To handle the divisor by zero error, use a new
construct called the try-catch block to enable the
program to catch the error and continue to
execute.
public class test1
{
public static void main(String [] args)
{
try
{
System.out.println(3/0);
}
catch (Exception ex)
{
System.out.println("Error:" + ex.getMessage());
}
System.out.println("Execution continues");
}
}
9. Exceptions and Exception Types
Various reasons for runtime error:
The user enters an invalid input – the program may try to
open a file that does not exist
the network connection may hang up
the program may try to access an out of bound s array
element
When an exception occurs, however, the program may
terminate if no handler can be used to deal with it.
10. Catching Exceptions
try {
statements; //Statement that may throw
//exceptions
}
catch (Exception1 ex) {
handler for exception1
}
catch (Exception2 ex) {
handler for exception2
}
...
catch (ExceptionN ex) {
handler for exceptionN
}
If no exceptions arise during the execution
of the try clause,the catch clauses are skipped.
11. 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.
12. Catch Runtime Errors
1 import java.util.*;
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 } while (continueInput);
25 }
13 }
14. System Errors
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.
16. Runtime Exceptions
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
17. Classifying Java Exceptions
Unchecked Exceptions Checked Exceptions
It is not required that these types of Must either be caught by a method or
exceptions be caught or declared on a declared in its signature.
method. Placing exceptions in the method
Runtime exceptions can be generated by signature harkens back to a major
methods or by the JVM itself. concern for Goodenough.
Errors are generated from deep within This requirement is viewed with
the JVM, and often indicate a truly fatal derision in the hardcore C++
state. community.
Runtime exceptions are a source of A common technique for simplifying
major controversy! checked exceptions is subsumption.
18. Keywords for Java Exceptions
throws
Describes the exceptions which can be raised by a method.
throw
Raises an exception to the first available handler in the call stack, unwinding the
stack along the way.
try
Marks the start of a block associated with a set of exception handlers.
catch
If the block enclosed by the try generates an exception of this type, control moves
here; watch out for implicit subsumption.
finally
Always called when the try block concludes, and after any necessary catch handler is
complete.
19. Canonical Example
public void foo() {
try { /* marks the start of a try-catch block */
int a[] = new int[2];
a[4] = 1; /* causes a runtime exception due to the index */
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
}
}
/* This code also compiles, but throws an exception at runtime! It
* is both less obvious and more common (an off-by-one-error). */
public int[] bar() {
int a[] = new int[2];
for (int x = 0; x <= 2; x++) { a[x] = 0; }
return a;
}
21. Trace a Program Execution
Suppose no exceptions in
the statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
22. Trace a Program Execution
The final block is always
executed
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
23. Trace a Program Execution
Next statement in the
method is executed
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
24. Trace a Program Execution
try { Suppose an exception of type
Exception1 is thrown in
statement1; statement2
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
25. Trace a Program Execution
try { The exception is handled.
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
26. Trace a Program Execution
try { The final block is always
executed.
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
27. Trace a Program Execution
try { The next statement in the
method is now executed.
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
28. Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type Exception2.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
30. 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;
31. Trace a Program Execution
try {
statement1; Rethrow the exception and
statement2; control is transferred to the
caller
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
32. 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.
33. 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.
34. 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");
}
35. 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");
Editor's Notes
Runtime exceptions make it impossible to know what exceptions can be emitted by a method. They also result in incosistent throws decls among developers. Describe subsumption to people: subsumption is often how IOException derivatives are dealt with (subsumption is casting to the base class). The most vituperative debate is between those who believe unchecked exceptions make mechanical testing nearly impossible, and those who believe that checked exceptions impinge on polymorphism by making the exception list part of the method signature (and thereby inheritable).