The document discusses exception handling in Java. It defines exceptions as abnormal conditions that occur during program execution. Java provides keywords like try, catch, throw and finally to handle exceptions. The document explains different types of exceptions like checked exceptions that must be handled and unchecked exceptions. It also covers how to define custom exception classes, throw and propagate exceptions, and use multiple catch blocks to handle different exception types.
3. www.SunilOS.com 3
Exception
It will cause abnormal termination of program or wrong
execution result.
Java provides an exception handling mechanism to handle
exceptions.
Exception handling will improve the reliability of application
program.
Java creates different type of objects in case of different
exceptional conditions that describe the cause of exception.
4. www.SunilOS.com 4
Exception Definition
Treat exception as an object.
All exceptions are instances of a class extended
from Throwable class or its subclass.
Generally, a programmer can make new
exception class by extending the Exception
class which is subclass of Throwable class.
5. www.SunilOS.com 5
Hierarchical Structure of Throwable Class
ObjectObject
ThrowableThrowable
ErrorError ExceptionException
RuntimeExceptionRuntimeException
...
...
...
6. www.SunilOS.com 6
Exception Types
Error Class
o Abnormal conditions those
can NOT be handled are
called Errors.
Exception Class
o Abnormal conditions those
can be handled are called
Exceptions.
8. www.SunilOS.com 8
Exception Handling
Exception handling is managed by five keywords try, catch, throw,
throws, and finally.
Exceptions can be generated by
o Java “run-time system” are called System-generated exceptions. It
is automatically raised by Java run-time system.
o Your code are called Programmatic Exceptions. It is raised by
throw keyword.
When an exceptional condition arises, an object is created that contains
exception description.
Handling is done with help of try-catch-finally block.
Exception raised in try block is caught by catch block.
Block finally is optional and always executed.
10. Uncaught Exception
public class TestArithmetic {
public static void main(String[] args) {
o int k = 0;
o int i = 15;
o double div = i / k;
o System.out.println("Div is " + div);
}}
www.SunilOS.com 10
Output
java.lang.ArithmeticException: / by zero
at TestArithmetic .main(TestArithmetic .java:5)
JVM detects that number is divided by zero that will produce infinity.
Since infinity can be stored that is why it makes a new exception object
and then throws this exception.
Output
java.lang.ArithmeticException: / by zero
at TestArithmetic .main(TestArithmetic .java:5)
JVM detects that number is divided by zero that will produce infinity.
Since infinity can be stored that is why it makes a new exception object
and then throws this exception.
11. Stack Trace
Exception Output
www.SunilOS.com 11
Exception class Exception Message
Exception Line Number
JVM detects the attempt to divide by zero, it makes new
exception object.
java.lang.ArithmeticException: / by zero
at TestArithmetic .main( TestArithmetic .java:5)
12. Handle Exception
public class TestArithmetic {
public static void main(String[] args) {
o int k = 0; int i = 15;
o try {
• double div = i / k;
• System.out.println("Div is " + div);
o } catch (ArithmeticException e) {
• System.out.println(“Divided by Zero");
o }
}}
www.SunilOS.com 12
Output
Divided by Zero
Notice that the call to println( ) inside the try block is never executed
Output
Divided by Zero
Notice that the call to println( ) inside the try block is never executed
13. Flow of execution
• try {
• a
• b //Throw Exception
• c
• } catch (Exception e) {
• d
• e
• } finally {
• f
• }
Normal Flow
a b c f
Exceptional Flow
a b d e f
www.SunilOS.com 13
14. Exception methods
Object received in catch block contains two key methods
o e.getMessage(); //displays error message.
• / by zero
o e.printStackTrace(); //displays complete trace of exception
• java.lang.ArithmeticException: / by zero
• at TestArithmetic .main( TestArithmetic .java:5)
www.SunilOS.com 14
15. Multiple catch blocks
More than one exception could be raised by a single try
block. To handle this type of situation, you can specify two
or more catch blocks.
String name = “Vijay”;
try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7th position is " + name.charAt(6));
} catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
} catch (NullPointerException e) {
o System.out.println(“Sundar sa nam nahi he!");
} finally {
o System.out.println(“Pandit hu me");
}
www.SunilOS.com 15
16. Multiple catch blocks (cont. )
More than one exception could be raised by a single try
block. To handle this type of situation, you can specify two
or more catch blocks.
String name = null;
try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7th position is " + name.charAt(6));
} catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
} catch (NullPointerException e) {
o System.out.println(“Sundar sa nam nahi he!");
} finally {
o System.out.println(“Pandit hu me");
}
www.SunilOS.com 16
17. Parent catch
String name = “Vijay”;
try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7 position is " + name.charAt(6));
} catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
} catch (RuntimeException e) {
o System.out.println(“Sundar sa nam nahi he!");
} finally {
o System.out.println(“Pandit hu me");
}
www.SunilOS.com 17
18. Generic Catch
A catch block of Parent Class can handle exceptions of its sub classes.
It can be used as a generic catch to handle multiple exceptions in down
hierarchy.
String name = “Vijay”;
try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7th position is " + name.charAt(6));
} catch (Exception e) {
o System.out.println(“Error ” + e.getMessage() );
}
www.SunilOS.com 18
19. Order of catch blocks: Parent & Child
Catch block of a Child class must come first in the order, if
Parent’s class catch does exist.
String name = “Vijay”;
try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7 position is " +
name.charAt(6));
} catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
} catch (RuntimeException e) {
o System.out.println(“Error “ + e,getMessage());
}
www.SunilOS.com 19
20. www.SunilOS.com 20
System-Defined Exception
It is raised implicitly by system because of illegal
execution of program when system cannot continue
program execution any more.
It is created by Java System automatically.
It is extended from Error class or RuntimeException class.
21. www.SunilOS.com 21
System-Defined Exception
IndexOutOfBoundsException:
o When beyond the bound of index in the object which use index, such as
array, string, and vector.
ArrayStoreException:
o When incorrect type of object is assigned to element of array.
NegativeArraySizeException:
o When using a negative size of array.
NullPointerException:
o When referring to object as a null pointer.
SecurityException:
o When security is violated.
IllegalMonitorStateException:
o When the thread which is not owner of monitor involves wait or notify
method.
23. Programmer Exception Class
class LoginException extends Exception { //Custom exception
o public LoginException() {
• super("User Not Found");
o }
}
class UserClass { //Raise custom exception
LoginException e = new LoginException();
// ...
if (val < 1) throw e;
}
}
Exception is raised by throw keyword.
www.SunilOS.com 23
24. www.SunilOS.com 24
Exception Occurrence
Raises implicitly by system.
Raises explicitly by programmer.
Syntax: throw exceptionObject
throw new LoginException();
Throwable class or
its sub class
25. www.SunilOS.com 25
Exception propagation
If there is no catch block to deal
with the exception, it is propagated
to calling method.
Unchecked exceptions are
automatically propagated.
Checked exceptions are propagated
by throws keyword.
returntype methodName(params)
throws e1, ... ,ek { }
Called method
Calling method
26. Exception propagation ( Cont.)
public static void main(String[] args) {
o try {
• authenticate (“vijay”);
o } catch (LoginException exp) {
• System.out.println(“Invalid Id/Passwod”);
o }
}
public static void authenticate ( String login) throws LoginException{
o If( !“admin”.equals(login)){
• LoginException e = new LoginException();
• throw e;
o }
}
www.SunilOS.com 26
27. Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 27