Download Chapter Five - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Kotebe University College
Department of Computer Science & Technology
Object Oriented Programming (CoSc2082)
5. Exception Handling
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.
5.1. Exception-Handling Overview
Program logic frequently tests conditions that determine how program execution should
proceed. Consider the following pseudo-code;
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 pseudo-code, 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.
The causes of exception
An exception is thrown for one of the three reasons:
1) An abnormal execution condition was synchronously detected by the JVM. Such conditions
arise because:
 Evaluation of an expression violates the normal semantics of the Java language, such as
an integer divided by zero.
 An error occurs in loading or linking part of the Java program
1
 Some limitation at recourse is executed, such as using too much memory
2) A throw statement was executed in Java code
3) An asynchronous exception occurred either because
 The method stop of class Thread was invoked
 An internal error has occurred in the virtual machine.
The Throwable class Hierarchy
A Java exception is an instance of the Throwable class or one of its extensions. Such an object
can be instantiated by running program in two ways: Either explicitly by a throw statement in
the program or implicitly by the Java run-time system when it is unable to execute a statement
in the program.
When an exception is thrown, it can be caught by a catch clause of a try statement. Using a try
statement to catch an exception is called exception handling.
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-time Exception 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
2
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.
5.2. Exception Handling Syntax
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());
}
Another code fragment that handles an ArithmeticException is
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());
}
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
}
...
private int quotient(int nume,int deno) throws ArithmeticException
4
{
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.
The throw statement
The throw statement causes an exception to be thrown. The result is an immediate transfer of
control that may exit multiple statements until a catch clause is found that catches the thrown
value.
The throw statement takes a single argument, an object of throwable class.
syntax: throw ThrowableInstance
Let us consider a simple example here:
public class ThrowDemo{
public static void main(String args[])
{
try{
throw new ArithmeticExcepion();
}
catch(ArithmeticException ae){
System.out....here
}
}
}//end class
The finally clause
Programs that obtain certain types of resources must return those resources to the system
explicitly to avoid so-called resource leaks. In programming languages such as C and C++, the
most common kind of resource leak is a memory leak. Java performs automatic garbage
collection to remove objects no longer used by programs, thus avoiding most memory leaks.
However, other types of resource leaks can occur in Java. For example, files, database
connections and network connections that are not closed properly might not 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.
5
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 handler will be 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.
User Defined Exceptions
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:
package javaexception;
public class UserDefinedException extends Exception{
/** Creates a new instance of UserDefinedException */
public UserDefinedException() {
System.out.println("Wrong data has been entered");
}
public UserDefinedException(String msg)
{
System.out.println(msg);
}
}
package javaexception;
public class UserTrial {
private int num1;
private int num2;
public UserTrial(int num1,int num2)
{
this.num1=num1;
this.num2=num2;
}
6
public void show() throws UserDefinedException
{
if(num1<0 || num2>0)
throw new UserDefinedException("Wrong data has been "+
"entered");
else
System.out.println("You entered : "+num1+" and"+
num2);
}
}
package javaexception;
public class Main {
public Main() {
}
/**
* @param args the command line arguments
* this example is more suitable if the program run from the
command line
* where the two arguments are supplied from command line
*/
public static void main(String[] args) {
UserTrial trial = new UserTrial(-1, 1);
try{
trial.show();
}
catch(UserDefinedException ude){
System.err.println("Illegal values entered");
}
}
}
7
Related documents