Chapter 7 ExceptionHandling
Chapter 7 ExceptionHandling
Exception Handling
- What is an exception?
- An exception is an error that occurs during the execution of a program. Java
facilitates the management of such errors by diverting control to special
program bocks that are called exception handlers.
- Exception handling enables programmers to create applications that can
resolve (or handle) exceptions. In many cases, handling an exception allows a
program to continue executing as if no problem had been encountered. These
features enable programmers to write robust and fault-tolerant programs.
Exception-Handling Overview
- Program logic frequently tests conditions that determine how program
execution should proceed. Consider the following psudocode;
Perform a task
If the preceding task did not execute correctly
Perform error processing
Perform next task
If the proceeding task did not execute correctly
Perform error processing
…
- In this psudocode, we begin by performing a task; then, we test whether that
task executed correctly or not. If not, we perform error processing. Otherwise,
we continue with the next task. Although this form of error handing works,
intermixing program logic with error-handling logic can make the program
difficult to read, modify and debug-especially in large applications.
Intermixing program and error-handling logic can degrade a program’s
performance, because the program must test the error-handling logic to
determine whether the next task can be performed.
- Exception handling enables the programmer to remove error-handling code
from the “main line” of the program’s execution, which improves program
clarity and enhances modifiability.
1
The method stop of class Thread was invoked
An internal error has occurred in the virtual machine.
- There are two kinds of exceptions: the kind that you can prevent by writing
better code, and the kind that you can’t. The first kind is called unchecked
exceptions. They are instances of the Error class, the run-timeException class,
and their extensions. For example, if the division of an integer by zero is
attempted, the system will generate an ArithmeticException.
- Exceptions of the second kind are called checked exceptions because they are
“checked” by the compiler before the program is run. Statements that throw
them either must be placed within a try statement, or they must be declared in
their method’s header. Checked exceptions are the kind that should be
expected and therefore managed by an exception handler.
2
Handling of an exception
- Java provides try statement to enable exception handling. A try statement
consists of keyword try, followed by braces ({}) that delimit a try block. The
try block contains statements that might cause exceptions and statements that
should not execute if an exception occurs. At least one catch clause (also
called an exception handler) or a finally clause must immediately follow the
try block. Each catch clause specifies in parenthesis, an exception parameter
that identifies the exception type the handler can process. The exception
parameter’s name enables the catch clause to interact with a caught exception
object. After the last catch handler, an optional finally clause provides code
that always execute, whether or not an exception occurs. A finally clause is an
ideal location for code that releases resources to prevent “resource leaks”.
- the general try statement in Java has this syntax:
try{
statements;
}catch(exception-type1 idetifier1){
statements;
}catch(exception-type2 identifier2){
statements;
}
...
finally{
statements;
}
- The point in the program at which an exception occur (i.e., the location where
a method detects and throws an exception) is called the throw point. If an
exception occurs in a try block, the try block terminates immediately and
program control transfers to the first catch clause that follows the try block.
This is known as the termination model of exception handling, because the try
block that encloses a thrown exception terminates when the exception occurs.
When a try block terminates, local variables declared in the block go out of
scope. Next the program searches for the first catch that can process the type
of exception that occurred. The program locates the matching catch by
comparing the thrown exception’s type with each catch’s exception-parameter
type until the program finds a match. A match occurs if the types are identical
or if the thrown exception’s type is a subclass of the exception parameter’s
type. When a match occurs, the code contained within the matching catch
handler executes. When a catch clause finishes processing, local variables
declared within the catch clause (including the catch parameter) go out of
scope. Any remaining catch clauses that correspond to the try block are
ignored and execution resumes at the first line of code after the try/catch
sequence.
3
- If no exceptions occur in a try block, the program ignores the catch handler(s)
for that block. If a finally clause appears after the last catch clause, the finally
clause executes regardless of whether an exception occurs.
- If an exception occurs in a method and is not caught, or the statement that
caused the exception is not in a try block, the method that contains the
statement terminates immediately, and the program attempts to locate an
enclosing try block in the calling method. This process is called stack
unwinding.
- let us consider how to handle an exception using try-catch statement:
try{
num1 = Integer.parseInt(n1);
num2 = Integer.parseInt(n2);
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,nfe.getMessage());
}
try{
ans = num1/num2;
JOptionPane.showMessageDialog(null,ans);
}
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
}
- The other way of exception handling is by using the keyword throws. This
keyword is used along methods. If a method is capable of raising an exception
that it does not handle, it must specify that the exception should be handled by
the calling method. This is done by the throws keyword.
- let us see an example here:
try{
num1 = Integer.parseInt(firstNumber);
num2 = Integer.parseInt(secondNumber);
result = quotient(num1,num2);//throws an ArithmeticException
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,nfe.getMessage());
}
4
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
...
private int quotient(int nume,int deno) throws ArithmeticException
{
return nume/deno;
}
- In the above code, the private method called quotient is declared with the
keyword throws in the method header definition. This shows that the
statement return nume/deno; in the body of the method is capable of throwing
an ArithmeticException. But, there is no mechanism to handle the exception
inside the method body. Therefore, the method calling this method should
have a means to handle the exception.
catch(ArithmeticException ae){
System.out....here
}
}
}//end class
5
be available for use in other programs, or even later in the same program’s
execution.
- Java guarantees that a finally clause (if one is present following a try/catch
sequence) will execute whether or not an exception is thrown in the
corresponding try block or in any of its corresponding catch clauses. Java also
guarantees that a finally clause (if one is present) will execute if a try block
exits by using a return, break or continue statement.
- Resource-release code typically is places in a finally clause. Suppose a
resource is allocated in a try block. If no exception occurs, the catch handlers
are skipped and control proceeds to the finally clause, which frees the
resource. Control proceeds to the first statement after the finally clause. If an
exception does occur, the program skips the rest of the try block. If the
program catches the exception in one of the catch handlers, the program
processes the exception. Then the finally clause release the resource and
control proceeds to the first statement after the finally clause.
- If an exception that occurs in the try block can’t be caught by one of that try
block’s catch handlers, the program skips the rest of the try block and control
proceeds to the finally clause, which releases the resource. Then the program
passes the exception up the call (i.e., to the calling method), which attempts to
catch it. This process can occur many times.
- If a catch handler throws an exception, the finally clause still executes. Then
an exception is passed o the calling method.
- There might be situations in which you want to handle exceptions that are not
available in the exception classes of Java. Suppose you accept a user name
and a password from a user. While verifying this information, if the login
credentials do not match, you may need to generate an exception. For this
purpose, you can use a user defined exception.
- A new exception class must extend an existing exception class to ensure that
the class can be used with exception handling mechanism. Like any other
class, an exception class can contain fields and methods. The subclass of the
exception class inherits the methods provided by the Throwable class because
Throwable is the superclass for the Exception class.
- let us consider an example here:
6
package javaexception;
public class UserDefinedException extends Exception{
package javaexception;
7
package javaexception;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
UserTrial trial = new UserTrial(-1, 1);
try{
trial.show();
}catch(UserDefinedException ude){
System.err.println("Illegal values entered");
}
}
}