VIPS OOPS Unit 2 Exception Handling
VIPS OOPS Unit 2 Exception Handling
What is an Exception?
§ An exception is an event that occurs during the execution of a program
that disrupts the normal flow of instructions.
§ When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception
(throw an error).
§ When executing Java code, different errors can occur: coding errors
made by the programmer, errors due to wrong input, or other
unforeseeable things.
Exception Hierarchy
• All exception and error types are subclasses of class Throwable, which
is the base class of the hierarchy. One branch is headed by Exception.
This class is used for exceptional conditions that user programs should
catch. NullPointerException is an example of such an exception
Exception Hierarchy
Types of Exceptions
Error is an unexpected event that cannot be handled at runtime. Errors can terminate your
program. Most of the time, programs cannot recover from an error. Errors cannot be caught or
handled. They are generally caused by the environment in which the code is running. e.g, The
image below is seen by almost all the computer users.
Definition of Exception
An Exception is the occurrence of an event that can disrupt the normal flow of the program instructions.
Exceptions can be caught and handled in order to keep the program working for the exceptional situation as
well, instead of halting the program flow.If the exception is not handled, then it can result in the termination
of the program. Exceptions can be used to indicate that an error has occurred in the program.
When an exception occurs, it creates an exception object. It holds information about the name and
description of the exception and stores the program's state when the exception occurred.
To illustrate how easily this can be done, the following program includes a try block and a catch clause that processes the
ArithmeticException generated by the division-by-zero error:
class Exc2 {
public static void main(String args[]) {
int d, a; Output:
try { // monitor a block of code. This program generates the
following output:
d = 0;
a = 42 / d; Division by zero.
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error After catch statement
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}}
1. Prevent the exception from happening.
2. Catch it in the method in which it occurs, and either
a. Fix up the problem and resume normal execution.
b. Rethrow it.
c. Throw a different exception.
3. Declare that the method throws the exception.
4. With 1. and 2.a. the caller never knows there was an
error.
5. With 2.b., 2.c., and 3., if the caller does not handle the
exception, the program will terminate and display a
stack trace.
try
{
// Code which might throw an exception
// ...
}
catch(FileNotFoundException x)
{
// code to handle a FileNotFound exception
}
catch(IOException x)
{
// code to handle any other I/O exceptions
}
catch(Exception x)
{
// Code to catch any other type of exception
}
finally
{
// This code is ALWAYS executed whether an exception was thrown
// or not. A good place to put clean-up code. ie. close
// any open files, etc...
}
• For normal execution:
• try block executes, then finally block executes, then other statements
execute
• When an error is caught and the catch block throws an exception or returns:
• try block is interrupted
• catch block executes (until throw or return statement)
• finally block executes
• When error is caught and catch block doesn’t throw an exception or return:
• try block is interrupted
• catch block executes
• finally block executes
• other statements execute
• When an error occurs that is not caught:
• try block is interrupted
• finally block executes
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
finally
next step
Exception
"thrown" here
Thrown exception matched against
first set of exception handlers
Exception
handler
If it fails to match, it is matched against
next set of handlers, etc.
Exception
handler
If exception matches none of handlers,
program is abandoned
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Next statement in the
try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
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;
method1() { declare exception
method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catchexception catch (Exception ex) { throw new Exception(); throwexception
Process exception; }
} }
}
Every method must state the types of checked exceptions
it might throw. This is known as declaring exceptions.
OtherException
If your method is defined to throw an exception, you need not
catch it within your method
}
If you don’t want the exception to be handled in the same function you can use the
throws class to handle the exception in the calling function.
• We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception.
Demonstrate throw Example
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_x0002_handling
context and immediately throws a new instance of NullPointerException, which is is caught on the next line.
The exception is then rethrown.
class ThrowDemo {
public static void main(String
static void demoproc() {
args[]) {
try {
throw new try {
NullPointerException("demo");
demoproc();
} catch(NullPointerException e) {
System.out.println("Caught inside } catch(NullPointerException e) {
demoproc."); System.out.println("Recaught: " +
throw e; // rethrow the exception e);
}} Resulting output:
Caught inside demoproc.
}}}
Recaught:
java.lang.NullPointerException: demo
Throw incorrect example
// This program contains an error and will not To make this example compile,
compile.
you need to make two changes.
class ThrowsDemo {
static void throwOne() { First, you need to declare
System.out.println("Inside throwOne."); that throwOne( ) throws
throw new IllegalAccessException("demo"); IllegalAccessException.
} Second, main( ) must define a
public static void main(String args[]) { try/catch
throwOne();
statement that catches this
}
exception.
}
Throws corrected example
The corrected example is shown public static void main(String args[]) {
here: try {
// This is now correct. throwOne();
if (anAmount>balance)
throw new InsuffientFundsException("Not enough cash");
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
IOException
System errors are thrown by JVM
ArithmeticException
Exception AWTException and represented in the Error class.
The Error class describes internal
NullPointerException
RuntimeException
system errors. Such errors rarely
IndexOutOfBoundsException
Object Throwable Several more classes occur. If one does, there is little you
canIllegalArgumentException
do beyond notifying the user and
LinkageError trying toclasses
Several more terminate the program
gracefully.
VirtualMachineError
Error
AWTError
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
(a) (b)
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to
it; an IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array.
These are the logic errors that should be corrected in the
program. Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-catch
blocks, Java does not mandate you to write code to catch
unchecked exceptions.
Java Catch Multiple Exceptions
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is
executed.
All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block
Multiple catch statements
/ Demonstrate multiple catch statements. catch(ArithmeticException e) {
class MultiCatch { System.out.println("Divide by 0: " + e);
public static void main(String args[]) { } catch(ArrayIndexOutOfBoundsException
try { e) {
int a = args.length; System.out.println("Array index oob: " + e);
System.out.println("a = " + a); }
int b = 42 / a;
Output: System.out.println("After try/catch blocks.");
int c[] = { 1 }; C:\>java MultiCatch }}
c[42] = 99; a=0
Divide by 0:
} java.lang.ArithmeticException:
/ by zero
After try/catch blocks.
Why use Custom Exceptions?
• Java exceptions cover almost all the general type of exceptions that
may occur in the programming. However, we sometimes need to
create custom exceptions.
• To catch and provide specific treatment to a subset of existing Java
exceptions.
• Business logic exceptions: These are the exceptions related to
business logic and workflow. It is useful for the application users or
the developers to understand the exact problem.
Custom Exception
• Consider the following example, where we create a custom exception
named WrongFileNameException:
super(errorMessage);
}
}
Custom Exception Example
/ This program creates a custom exception type. static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
class MyException extends Exception {
if(a > 10) Output:
private int detail; This example Called compute(1)
throw new MyException(a);
MyException(int a) { defines a subclass Normal exit
of Exception System.out.println("Normal exit");
Called compute(20)
detail = a; called } Caught
} MyException. public static void main(String args[]) { MyException[20]
public String toString() { This subclass is try {
quite compute(1);
return "MyException[" + detail + "]";simple: it has
compute(20);
} only a
} catch (MyException e) {
constructor plus
}
an overloaded System.out.println("Caught " + e);
class ExceptionDemo { toString( ) }}
method that
displays the
Example 1:Custom Exception
Simple example of Java custom • A l s o t h e c o n s t r u c t o r o f
exception. In the following code, Exception class can be called
c o n s t r u c t o r o f without using a parameter and
InvalidAgeException takes a calling super() method is not
string as an argument. This string m a n d a t o r y .
is passed to constructor of parent
class Exception using the super() TestCustomException1.java
method.
Java Custom Exception
• In Java, we can create our own exceptions • Using the custom exception, we
that are derived classes of the Exception
class. Creating our own Exception is
can have your own exception
known as custom exception or user- and message. Here, we have
defined exception. Basically, Java custom passed a string to the constructor
exceptions are used to customize the of superclass i.e. Exception class
exception according to user need.
that can be obtained using
getMessage() method on the
• Consider the example 1 in which object we have created.
InvalidAgeException class extends the
Exception class.
Example Custom Exception
// throw an object of user defined exception
// class representing custom exception
throw new InvalidAgeException("age is not valid for vote"); }
class InvalidAgeException extends Exception
else {
{
System.out.println("welcome to vote");
public InvalidAgeException (String str)
} } // main method
{ public static void main(String args[])
// calling the constructor of parent Exception { try
super(str); { // calling the method
} } // class that uses custom exception InvalidAgeException validate(13); }