Lesson 10 - Exception in Java (1)
Lesson 10 - Exception in Java (1)
Exception in Java
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a runtime error.
A Java exception is an object that describes an exceptional condition that has occurred in a
piece of code. When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error. That method may choose to handle
the exception itself or pass it on.
After a method throws an exception, the runtime system attempts to find something to handle
it. The set of possible "somethings" to handle the exception is the ordered list of methods that
had been called to get to the method where the error occurred. The list of methods is known
as the call stack.
The runtime system searches the call stack for a method that contains a block of code that can
handle the exception. This block of code is called an exception handler. The search begins
with the method in which the error occurred and proceeds through the call stack in the reverse
order in which the methods were called. When an appropriate handler is found, the runtime
system passes the exception to the handler. An exception handler is considered appropriate if
the type of the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system
exhaustively searches all the methods on the call stack without finding an appropriate
exception handler, as shown in the below figure, the runtime system (and, consequently, the
program) terminates.
• A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Exception Types
All exception types are subclasses of the built-in class Throwable. Immediately below
Throwable are two subclasses.
❖ Exception
❖ Error
Exception
• This class is used for exceptional conditions that user programs should catch.
• This is also the class that you will subclass to create your own custom exception
types.
• There is an important subclass of Exception, called RuntimeException. Exceptions of
this type are automatically defined for the programs that you write and include things
such as division by zero and invalid array indexing.
Error
• Defines exceptions that are not expected to be caught under normal circumstances by
your program.
• Exceptions of type Error are used by the Java run-time system to indicate errors
having to do with the run-time environment, itself.
• Stack overflow is an example of such an error.
Checked Exception
Unchecked Exception
1) To guard against and handle a run-time error, simply enclose the code that you want
to monitor inside a try block.
2) Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
class Exc2 {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output
Division by zero.
After catch statement.
• Once an exception is thrown, program control transfers out of the try block into
the catch block, that is why println( ) inside the try block is never executed.
• Put differently, catch is not “called,” so execution never “returns” to the try block
from a catch. Thus, the line "This will not be printed." is not displayed.
• Once the catch statement has executed, program control continues with the next
line in the program following the entire try/catch mechanism.
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown, each catch statement is inspected in order,
and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continues after the try/catch
block.
class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their superclasses. This is because a catch statement that
uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass
would never be reached if it came after its superclass. Further, in Java, unreachable code is an
error. For example, consider the following program:
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
}
catch(Exception e) {
System.out.println("Generic Exception catch.");
}
catch(ArithmeticException e) { // ERROR
System.out.println("This is never reached.");
}
}
}
The program works as follows. When you execute the program with no command-line
arguments, a divide-byzero exception is generated by the outer try block. Execution of the
program with one command-line argument generates a divide-by-zero exception from within
the nested try block. Since the inner block does not catch this exception, it is passed on to the
outer try block, where it is handled. If you execute the program with two command-line
arguments, an array boundary exception is generated from within the inner try block.
Using throw
• So far, you have only been catching exceptions that are thrown by the Java run-time
system.
• However, it is possible for your program to throw an exception explicitly, using the
throw statement.
• The general form of throw is shown here:
throw ThrowableInstance;
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside
demoproc.");
throw e; // rethrow the exception
}
}
This program gets two chances to deal with the same error. First, main( ) sets up an
exception context and then calls demoproc( ). The demoproc( ) method then sets up.
Another exception-handling context and immediately throws a new instance of
NullPointerException, which is caught on the next line. The exception is then rethrown.
Using throws
• If a method can cause an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
• It is achieved by including a throws clause in the method’s declaration.
• A throws clause lists the types of exceptions that a method might throw.
Suppose throwOne throw two exceptions, then the syntax will be the following.
Using finally
The finally block always executes when the try block exits. This ensures that
the finally block is executed even if an unexpected exception occurs. But finally is useful for
more than just exception handling — it allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block
is always a good practice, even when no exceptions are anticipated.
class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}
}
procB();
procC();
}
}
Output
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The
finally clause is executed on the way out. procB( )’s try statement is exited via a return
statement. The finally clause is executed before procB( ) returns. In procC( ), the try
statement executes normally, without error. However, the finally block is still executed.
Java’s built-in exceptions handle most common errors, you will probably want to create your
own exception types to handle situations specific to your applications. This is quite easy to
do: just define a subclass of Exception (which is, of course, a subclass of Throwable). Your
subclasses don’t need to actually implement anything—it is their existence in the type system
that allows you to use them as exceptions.
See the following example, we have an Account class, which is representing a bank account
where you can deposit and withdraw money, but what will happen if you want to withdraw
money which exceeds your bank balance? You will not be allowed, and this is where user
defined exception comes into the picture. We have created a custom exception
called NotSufficientFundException to handle this scenario. This will help you to show a
more meaningful message to user and programmer.
class NotSufficientFundException extends Exception {
private String message;
public NotSufficientFundException(String message) {
this.message = message;
}
public String getMessage() { return message; }
}
Exercise