3. 10-3
Exceptions
• An exception is an object that describes an
unusual or erroneous situation
• Exceptions are thrown by a program, and may be
caught and handled by another part of the
program
• A program can be separated into a normal
execution flow and an exception execution flow
• An error is also represented as an object in Java,
but usually represents a unrecoverable situation
and should not be caught
4. 10-4
Exception Handling
• Java has a predefined set of exceptions and errors
that can occur during execution
• A program can deal with an exception in one of
three ways:
ignore it
handle it where it occurs
handle it an another place in the program
• The manner in which an exception is processed is
an important design consideration
5. 10-5
Exception Handling
• If an exception is ignored by the program, the
program will terminate abnormally and produce
an appropriate message
• The message includes a call stack trace that:
indicates the line on which the exception occurred
shows the method call trail that lead to the attempted
execution of the offending line
6. GENERAL FORM
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
} 10-6
7. 10-7
The try Statement
• To handle an exception in a program, the line that
throws the exception is executed within a try block
• A try block is followed by one or more catch
clauses
• Each catch clause has an associated exception
type and is called an exception handler
• When an exception occurs, processing continues
at the first catch clause that matches the
exception type
8. 10-8
The finally Clause
• A try statement can have an optional clause
following the catch clauses, designated by the
reserved word finally
• The statements in the finally clause always are
executed
• If no exception is generated, the statements in the
finally clause are executed after the statements in
the try block complete
• If an exception is generated, the statements in the
finally clause are executed after the statements in
the appropriate catch clause complete
9. Keyword Description
try The "try" keyword is used to specify a block where we
should place exception code. The try block must be
followed by either catch or finally. It means, we can't use
try block alone.
catch The "catch" block is used to handle the exception. It
must be preceded by try block which means we can't use
catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code
of the program. It is executed whether an exception is
handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It
doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.
10-9
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
10. 10-10
Exception Propagation
• An exception can be handled at a higher level if it
is not appropriate to handle it where it occurs
• Exceptions propagate up through the method
calling hierarchy until they are caught and handled
or until they reach the level of the main method
• A try block that contains a call to a method in
which an exception is thrown can be used to catch
that exception
13. 10-13
The Exception Class Hierarchy
• Classes that define exceptions are related by
inheritance, forming an exception class hierarchy
• All error and exception classes are descendents of
the Throwable class
• A programmer can define an exception by
extending the Exception class or one of its
descendants
• The parent class used depends on how the new
exception will be used
14. 10-14
Checked Exceptions
• An exception is either checked or unchecked
• A checked exception either must be caught by a
method, or must be listed in the throws clause of
any method that may throw or propagate it
• A throws clause is appended to the method header
• The compiler will issue an error if a checked
exception is not caught or asserted in a throws
clause
15. 10-15
Unchecked Exceptions
• An unchecked exception does not require explicit
handling, though it could be processed that way
• The only unchecked exceptions in Java are
objects of type RuntimeException or any of its
descendants
• Errors are similar to RuntimeException and its
descendants in that:
Errors should not be caught
Errors do not require a throws clause
16. 1. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an
arithmetic operation.
2. ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or
equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose
definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not
open.
5. IOException
It is thrown when an input-output operation failed or interrupted
10-16
Built-in Exceptions
17. 6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some
processing , and it is interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable)
specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object.
Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into
a numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either
negative than the size of the string
10-17
18. // Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
} } 10-18
19. // Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e)
{
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}}} 10-19
20. Multiple catch
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
{System.out.println("common task completed");}
System.out.println("rest of the code...");
}
} 10-20
21. Nested try
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
} catch(ArithmeticException e) {System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
} catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);}
System.out.println("other statement);
} catch(Exception e) {System.out.println("handeled");}
System.out.println("normal flow..");
}
} 10-21
22. 10-22
The throw Statement
• 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;
Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
• Exceptions are thrown using the throw statement
• Usually a throw statement is executed inside an if statement that
evaluates a condition to see if the exception should be thrown.
• The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed. The nearest enclosing
try block is inspected to see if it has a catch statement that matches
the type of exception. If it does find a match, control is transferred to
that statement. If not, then the next enclosing try statement is
inspected, and so on. If no matching catch is found, then the default
exception handler halts the program and prints the stack trace.
23. // Java program that demonstrates the use of throw
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
} } } 10-23
24. Throws
If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception. You do this by including a throws clause
in the method’s declaration. A throws clause lists the typesof exceptions that
a method might throw. This is necessary for all exceptions, except those of
type Error or RuntimeException, or any of their subclasses. All other
exceptions that a method can throw must be declared in the throws clause.
If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws
clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
10-24
25. Example - throws
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
10-25
26. Finally Block
• The finally block follows a try block or a catch block. A
finally block of code always executes, irrespective of
occurrence of an Exception.
• Using a finally block allows you to run any cleanup-type
statements that you want to execute, no matter what
happens in the protected code.
10-26
27. Finally example
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
10-27