Exception Handling
Dr.S.Amarnadh
Assistant Professor, Dept. of Computer Science And Engineering
GITAM School of Technology
Department of Computer Science and Engineering 1
Scenario
Meera is flying to NewYork
What are these?
Department of Computer Science and Engineering 2
Scenario Cont..
The previous slide depicts an air hostess giving a demonstration of steps
that we have to take as passengers, in case of emergency.
Why this demonstration is important?
Why the air line staff insists on wearing our seat belts?
Department of Computer Science and Engineerin 3
g
Scenario Cont..
• You have to be aware of how to tackle a situation in case of an
emergency while you are flying aboard an aircraft.
• You have to fasten your seat belts to protect yourself from mishaps
that can occur during take off and landing.
• This example demonstrates how you have to think in advance the
many possibilities of mishaps that can occur and what are the
preventive measures that can be taken.
Department of Computer Science and Engineerin 4
g
Scenario Cont..
• Similarly, when we write programs as part of an application, we may
have to visualize the challenges that can disrupt the normal flow of
execution of the code.
• Once we know what are the different situations that can disrupt the
flow of execution, we can take preventive measures to overcome
these disruptions.
• In java,this mechanism comes in the form of Exception
Handling.
Department of Computer Science and Engineerin 5
g
Errors in Java Program
6
Department of Computer Science and Engineering
Compile-time errors: Examples
Class Error {
Public static void main (string args [ ]) {
system.out.print(“Can you find errors in
me?”)
}
}
class AnotherError {
public void insert( ){
System.out.print(“To insert a text”);
}
abstract void delete( ){
System.out.print(“To delete a text”);
}
}
Department of Computer Science and Engineering 7
Some common compile-time errors
• Missing semicolons.
• Missing (or mismatch of brackets) in classes and methods.
• Misspelling of identifiers or keywords.
• Missing double quotes in strings.
• Use of undeclared variables.
• Incomplete types in assignment / initialization.
•Bad references to objects. and many more ….
Department of Computer Science and Engineering 8
Run-time errors: Examples
class Error {
public static void main (String args [ ]) {
int a = Integer.parseInt(args[0]};
int b = Integer.parseInt(args[1]};
int c = a/b;
System.out.println(“Value of c =“ + c);
}
}
Department of Computer Science and Engineering 9
Some common run-time errors
•A user has entered invalid data.
•Dividing an integer by zero.
•Accessing an element that is out of the bounds of an array.
•Trying to store a value into an array of an incomplete class or type.
•Trying to cast an instance of a class to one of its subclasses.
•Trying to illegally change the state of a thread.
•Attempting use a negative size for an array.
•Null object reference.
•A file that needs to be opened cannot be found.
•A network connection has been lost in the middle of communicat
Department of Computer Science and Engineering 10
Errors and exceptions in Java
Whenever an Error or Exception occurs, Java Run-Time Environment throws an
object corresponding to that.
Examples:
Java Run-Time Environment throws an object called IllegalArumentType
when a method m(int x, int y) is called as m(1.5, 4);
Java Run-Time Environment throws an object called ArithmeticException
when a = x/(b – c); and b = c;
Department of Computer Science and Engineering
Exception Types
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Department of Computer Science and Engineering
System Errors
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
System errors are thrown by JVM LinkageError
and represented in the Error class.
The Error class describes internal
Error VirtualMachineError
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the Many more classes
user and trying to terminate the
program gracefully.
Department of Computer Science and Engineering
Exceptions
Exception describes errors caused
ClassNotFoundException
by your program and external
circumstances. These errors can ArithmeticException
be caught and handled by your IOException
program. Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Department of Computer Science and Engineering
Runtime ExceptionsRuntime Exception is caused by
programming errors, such as bad
casting, accessing an out-of-
ClassNotFoundException bounds array, and numeric errors
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Department of Computer Science and Engineering
Checked Exceptions vs. Unchecked Exceptions
RuntimeException, Error and their subclasses are known as unchecked exceptions.
All other exceptions are known as checked exceptions, meaning that the compiler
forces the programmer to check and deal with the exceptions
16
Department of Computer Science and Engineering
Unchecked Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Department of Computer Science and Engineering
Runtime Exception sub classes
Department of Computer Science and Engineering
Exception sub classes
Department of Computer Science and Engineering
Error classes
Department of Computer Science and Engineering
Exception handling in Java
• Java provides Run Time Error Management to deal with errors and exceptions.
• During the execution of a program, when an exceptional condition arises, an
object of the respective exception classes is created and thrown in with
method which caused the exception.
• That method may choose to catch the exception and then can guard against
premature exit or may have a block of code to execute.
• Java exception handling is managed via five keywords:
21
Department of Computer Science and Engineering
Exception handling in Java
22
Department of Computer Science and Engineering
Catching Exceptions
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
Call Stack
method3
method2 method2
method1 method1 method1
main method main method main method main method
23
Department of Computer Science and Engineering
Exception handling in Java
Simple try- try with Multiple exceptions Exception with Throwing own Nested try-catch
catch multiple catch exit code exception block
Multiple Throws/
try with try-catch throw in try- try within
try with a exception with finally another try
multiple block
single catch with one
catch
catch
24
Department of Computer Science and Engineering
Simple try-catch
25
Department of Computer Science and Engineering
Simple try-catch: Example
class DivideZero {
static int anyFunction ( int x, int y )
{
int a = x/y;
return (a);
}
Public static void main (String args [] )
{
int result = anyFunction (25, 0) ;// Exception occurs here
as y = 0
System.out.println ( “ Result : ” + result );
}
}
26
Department of Computer Science and Engineering
class DivideZero {
Simple try-catch: Example
static int anyFunction (int x, int y )
{
try {
int a = x/y;
return(a);
}
catch (ArithmeticException e) {
System.out.println ( “a = x/y is bypassed… Enter y as non- zero” );
}
}
public static void main (String args[ ] {
int a,b, result;
system.out.print(“Enter any two integers : “);
a = System.in.read( );
b = System.in.read( );
result = any Function (a, b);
System.out.println ( “Result : ” + result);
}
} 27
Department of Computer Science and Engineering
try-catch: Making program robust
28
Department of Computer Science and Engineering
try with Multiple catch:
29
Department of Computer Science and Engineering
try with Multiple catch:
30
Department of Computer Science and Engineering
Multiple errors with single catch
31
Department of Computer Science and Engineering
finally in try-catch
32
Department of Computer Science and Engineering
finally in try-catch
33
Department of Computer Science and Engineering
throw in try-catch
34
Department of Computer Science and Engineering
throw in try-catch: Example
35
Department of Computer Science and Engineering
throws in try-catch
type method-name(parameter-list) throws exception-list
{
// body of method
}
36
Department of Computer Science and Engineering
throws in try-catch
37
Department of Computer Science and Engineering
Nested try-catch
38
Department of Computer Science and Engineering
Declaring your own exception
All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the
Handle or
Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the
RuntimeException class
Syntax
class MyException extends Exception
{
...
}
39
Department of Computer Science and Engineering
Declaring your own exception
40
Department of Computer Science and Engineering
Thank You
Department of Computer Science and Engineering