SlideShare a Scribd company logo
Exception Handling
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
2
Why?
 Users may use our programs in an unexpected ways.
 Due to design errors or coding errors, programs may fail in
unexpected ways during execution, or may result in an
abnormal/abrupt program termination
 It is programmer’s responsibility to produce robust code
that does not fail unexpectedly.
 Consequently, programmer must design error handling
into our programs.
 Java – provides clear mechanism to Handle the Exceptions
that happen during program execution.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
3
What you know…
 In C, using the term “ERROR” is used to represent the
unexpected interruption of code execution.
 Two types:
 Compile time Errors (Syntax and Semantic error)
 Runtime Errors (errors)
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
4
Common Runtime Errors
 Dividing a number by zero.
 Accessing an element that is out of bounds of an
array.
 Trying to store incompatible data elements.
 Using negative value as array size.
 Trying to convert from string data to a specific data
value (e.g., converting string “abc” to integer value).
 File errors:
 Opening the file that does not exist
 opening a file in “read mode” that does not exist or
no read permission
 Opening a file in “write/update mode” which has
“read only” permission.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
5
Exceptions Handling in Java
 An abnormal condition that arises in a code sequence at
run time.
 In other words, an exception is a run-time error.
 A Java exception is an object that describes an
exceptional (that is, error) 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.
 A program can deal with an exception object in one of
three ways:
 ignore it
 handle it where it occurs
 handle it an another place in the programDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
6
Exceptions Handling in Java
 Java provides a robust and object oriented way to handle
exception scenarios, known as Java Exception Handling.
 Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.
 Program statements that you want to monitor for
exceptions are contained within a try block.
 Catch block can handle it in some rational manner.
 System-generated exceptions are automatically thrown by the Java
run-time system.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be
specified as such by a throws clause.
 Any code that must be executed after a try block
completes (with/without exception)is put in a finally block.Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
7
Syntax of Exception Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
8
Without Exception Handling
class WithoutExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
r = a/b;
System.out.println(“Result is “ + r);
System.out.println(“Program reached this line”);
}
} Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
9
With Exception Handling
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Program
Reaches here
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
10
Exception Hierarchy
 All exception types are subclasses of the built-in class
Throwable.
 Throwable is at the top of the exception class hierarchy.
 Throwable are two subclasses partition exceptions into
two distinct branches.
 Exceptions
 Errors
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
11
Java Exception Class Hierarchy
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
12
Exception Class
 Exception is used for exceptional conditions that user
programs should catch.
 This class is inherited to create subclass as programmer’s
own custom exception types.
 There is an important subclass of Exception, called
RuntimeException.
 Exceptions of this type are automatically defined for the
programs that a programmer write.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
13
Exception Class
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
14
Runtime Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
15
Error Exception
 The 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.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
16
Error Exception Types
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
17
Error Exception Types
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
18
Poll Question
 Consider the JVM stops execution of a java program due
to shortage of JVM memory. This scenario is
 A. Runtime Exception
 B. Error
 C. Checked Exception
 D. Exception
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
19
Exception Types
 Exceptions fall into two categories:
 Checked Exceptions
 Unchecked Exceptions
 Checked exceptions are inherited from the core Java class
Exception.
 represent compile time exceptions that are coder responsibility to
check.
 the compiler will issue an error message.
 RuntimeException, Error and their subclasses are known
as unchecked exceptions.
 if not handled, your program will terminate with an appropriate
error message.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
20
Exception Types
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
21
Exception Types
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Unchecked
exception.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
22
what happens when don’t handle
The call stack is quite useful for debugging, because it pinpoints the
precise sequence of steps that led to the errorDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Predict the output
23Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
24
Poll Question
Output??
 A Compile Error
 B Inside
 C Inside
rest of the code
 D Inside
Null
rest of the code
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Handling Exception
 Different mechanism.
 Simple try - catch
 try with multiple catch
 multiple exception with single catch
 nested try statements
 throw
 Throws
 try, catch and finally (exception with exit code)
 Java Exception Propagation
25Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Simple try - catch
 The try block allows you to define a block of code to be
tested/monitor for errors while it is being executed.
 The catch block allows you to define a block of code to be
executed, if an error occurs in the try block.
26Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Example
27Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Try with multiple catch
 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
28Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Try with multiple catch Ex
29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
multiple exception with single catch
 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.
30Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
multiple exception with single catch Ex
31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
multiple exception with single catch Ex
32Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
nested try statements
 The try statement can be nested.
 That is, a try statement can be inside the block of another
try.
 If an inner try statement does not have a catch handler
for a particular exception, the stack is unwound and the
next try statement’s catch handlers are inspected for a
match.
 This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted.
 If no catch statement matches, then the Java run-time
system will handle the exception
33Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
nested try statements Ex
34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
35
Poll Question
 Which of these is a super class of all errors and exceptions
in the Java language?
 A RunTimeExceptions
 B Throwable
 C Catchable
 D None of the above
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Handling Exception
 Different mechanism.
 Simple try - catch
 try with multiple catch
 multiple exception with single catch
 nested try statements
 throw
 Throws
 try, catch and finally (exception with exit code)
 Java Exception Propagation
36Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
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.
 Syntax:
 Here, ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
 The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed.
 If no matching catch is found, then the default exception
handler halts the program and prints the stack trace
37Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
throw
38Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
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 types of exceptions that a
method might throw.
 This is necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses.
 If they are not, a compile-time error will result.
39Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Throws
 This is the general form of a method declaration that
includes a throws clause:
 exception-list is a comma-separated list of the exceptions
that a method can throw.
 First, you need to declare that throwOne( ) throws
IllegalAccessException.
 Second, main( ) must define a try/catch statement that
catches this exception.
40Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Throws
41Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Throws
42Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
try, catch and finally
 When exceptions are thrown, execution in a method takes
a rather abrupt, nonlinear path that alters the normal
flow through the method.
 This could be a problem in some methods. For example,
 if a method opens a file upon entry and closes it upon
exit,
 then you will not want the code that closes the file to
be bypassed by the exception-handling mechanism.
 The finally keyword is designed to address this
contingency
43Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
try, catch and finally
 finally creates a block of code that will be executed after
a try/catch block has completed and
 before the code following the try/catch block.
 The finally block will execute whether or not an exception
is thrown.
44Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
try, catch and finally
45Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Java’s Built-in Exceptions
 Inside the standard package java.lang, Java defines
several exception classes.
 A few have been used by the preceding examples.
46Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Java’s Built-in Exceptions
47Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Java’s Built-in Exceptions
48Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
 Although Java’s built-in exceptions handle most common
errors
 user 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).
class UserException extends Exception
{
}
49Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
class InvalidMobile extends Exception
{
InvalidMobile(String msg)
{
super(msg);
}
}
50Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
51Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
52Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
53
The End…
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam

More Related Content

PPTX
I/O Streams
PPT
Java Streams
PPTX
Interfaces in java
PPTX
Type casting in java
PPTX
File handling
PPTX
java interface and packages
PPS
Wrapper class
PPT
Exception Handling in JAVA
I/O Streams
Java Streams
Interfaces in java
Type casting in java
File handling
java interface and packages
Wrapper class
Exception Handling in JAVA

What's hot (20)

PPSX
Data Types & Variables in JAVA
PPT
Java-java virtual machine
PPTX
Java awt (abstract window toolkit)
PPTX
Final keyword in java
PPTX
L14 exception handling
PPTX
This keyword in java
PPTX
Interface in java
PPTX
MULTI THREADING IN JAVA
PDF
PDF
Java Course 8: I/O, Files and Streams
PPTX
Control statements in java
PPTX
Core java complete ppt(note)
PPTX
Polymorphism in java
PDF
Exception Handling in Java
PPTX
Java package
PPTX
Static Members-Java.pptx
PPTX
Java – lexical issues
PPTX
Exception Handling in Java
PPTX
Access modifiers in java
Data Types & Variables in JAVA
Java-java virtual machine
Java awt (abstract window toolkit)
Final keyword in java
L14 exception handling
This keyword in java
Interface in java
MULTI THREADING IN JAVA
Java Course 8: I/O, Files and Streams
Control statements in java
Core java complete ppt(note)
Polymorphism in java
Exception Handling in Java
Java package
Static Members-Java.pptx
Java – lexical issues
Exception Handling in Java
Access modifiers in java
Ad

Similar to Java - Exception Handling Concepts (20)

PPT
Exception handling
PPSX
Java Exceptions
PPSX
Java Exceptions Handling
PPTX
Exception handling in java
PPTX
Exceptionhandling
PPTX
java exception.pptx
PPTX
Exception handling
PDF
Exception handling
PPT
JP ASSIGNMENT SERIES PPT.ppt
PDF
16 exception handling - i
PPTX
Java exception handling
PPTX
Exception handling and throw and throws keyword in java.pptx
PPTX
Exceptions
PPTX
Exceptions
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Interface andexceptions
PDF
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPT
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Exception handling
Java Exceptions
Java Exceptions Handling
Exception handling in java
Exceptionhandling
java exception.pptx
Exception handling
Exception handling
JP ASSIGNMENT SERIES PPT.ppt
16 exception handling - i
Java exception handling
Exception handling and throw and throws keyword in java.pptx
Exceptions
Exceptions
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
Interface andexceptions
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
unit 4 msbte syallbus for sem 4 2024-2025
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Ad

More from Victer Paul (13)

PDF
OOAD - UML - Sequence and Communication Diagrams - Lab
PDF
OOAD - UML - Class and Object Diagrams - Lab
PDF
OOAD - Systems and Object Orientation Concepts
PDF
Java - Strings Concepts
PDF
Java - Packages Concepts
PDF
Java - OOPS and Java Basics
PDF
Java - Class Structure
PDF
Java - Object Oriented Programming Concepts
PDF
Java - Basic Concepts
PDF
Java - File Input Output Concepts
PDF
Java - Inheritance Concepts
PDF
Java - Arrays Concepts
PDF
Java applet programming concepts
OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Class and Object Diagrams - Lab
OOAD - Systems and Object Orientation Concepts
Java - Strings Concepts
Java - Packages Concepts
Java - OOPS and Java Basics
Java - Class Structure
Java - Object Oriented Programming Concepts
Java - Basic Concepts
Java - File Input Output Concepts
Java - Inheritance Concepts
Java - Arrays Concepts
Java applet programming concepts

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PDF
Sensors and Actuators in IoT Systems using pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
Empathic Computing: Creating Shared Understanding
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Transforming Manufacturing operations through Intelligent Integrations
PPTX
Cloud computing and distributed systems.
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
KodekX | Application Modernization Development
Sensors and Actuators in IoT Systems using pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Empathic Computing: Creating Shared Understanding
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
GamePlan Trading System Review: Professional Trader's Honest Take
NewMind AI Monthly Chronicles - July 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Transforming Manufacturing operations through Intelligent Integrations
Cloud computing and distributed systems.
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Advanced methodologies resolving dimensionality complications for autism neur...
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf

Java - Exception Handling Concepts

  • 1. Exception Handling Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 2. 2 Why?  Users may use our programs in an unexpected ways.  Due to design errors or coding errors, programs may fail in unexpected ways during execution, or may result in an abnormal/abrupt program termination  It is programmer’s responsibility to produce robust code that does not fail unexpectedly.  Consequently, programmer must design error handling into our programs.  Java – provides clear mechanism to Handle the Exceptions that happen during program execution. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 3. 3 What you know…  In C, using the term “ERROR” is used to represent the unexpected interruption of code execution.  Two types:  Compile time Errors (Syntax and Semantic error)  Runtime Errors (errors) Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 4. 4 Common Runtime Errors  Dividing a number by zero.  Accessing an element that is out of bounds of an array.  Trying to store incompatible data elements.  Using negative value as array size.  Trying to convert from string data to a specific data value (e.g., converting string “abc” to integer value).  File errors:  Opening the file that does not exist  opening a file in “read mode” that does not exist or no read permission  Opening a file in “write/update mode” which has “read only” permission. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 5. 5 Exceptions Handling in Java  An abnormal condition that arises in a code sequence at run time.  In other words, an exception is a run-time error.  A Java exception is an object that describes an exceptional (that is, error) 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.  A program can deal with an exception object in one of three ways:  ignore it  handle it where it occurs  handle it an another place in the programDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 6. 6 Exceptions Handling in Java  Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  Program statements that you want to monitor for exceptions are contained within a try block.  Catch block can handle it in some rational manner.  System-generated exceptions are automatically thrown by the Java run-time system.  To manually throw an exception, use the keyword throw.  Any exception that is thrown out of a method must be specified as such by a throws clause.  Any code that must be executed after a try block completes (with/without exception)is put in a finally block.Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 7. 7 Syntax of Exception Handling Code … … try { // statements } catch( Exception-Type e) { // statements to process exception } .. .. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 8. 8 Without Exception Handling class WithoutExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; r = a/b; System.out.println(“Result is “ + r); System.out.println(“Program reached this line”); } } Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 9. 9 With Exception Handling class WithExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); } System.out.println(“Program reached this line”); } } Program Reaches here Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 10. 10 Exception Hierarchy  All exception types are subclasses of the built-in class Throwable.  Throwable is at the top of the exception class hierarchy.  Throwable are two subclasses partition exceptions into two distinct branches.  Exceptions  Errors Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 11. 11 Java Exception Class Hierarchy LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 12. 12 Exception Class  Exception is used for exceptional conditions that user programs should catch.  This class is inherited to create subclass as programmer’s own custom exception types.  There is an important subclass of Exception, called RuntimeException.  Exceptions of this type are automatically defined for the programs that a programmer write. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 13. 13 Exception Class LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 14. 14 Runtime Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 15. 15 Error Exception  The 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. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 16. 16 Error Exception Types LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 17. 17 Error Exception Types Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 18. 18 Poll Question  Consider the JVM stops execution of a java program due to shortage of JVM memory. This scenario is  A. Runtime Exception  B. Error  C. Checked Exception  D. Exception Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 19. 19 Exception Types  Exceptions fall into two categories:  Checked Exceptions  Unchecked Exceptions  Checked exceptions are inherited from the core Java class Exception.  represent compile time exceptions that are coder responsibility to check.  the compiler will issue an error message.  RuntimeException, Error and their subclasses are known as unchecked exceptions.  if not handled, your program will terminate with an appropriate error message. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 20. 20 Exception Types Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 21. 21 Exception Types LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Unchecked exception. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 22. 22 what happens when don’t handle The call stack is quite useful for debugging, because it pinpoints the precise sequence of steps that led to the errorDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 23. Predict the output 23Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 24. 24 Poll Question Output??  A Compile Error  B Inside  C Inside rest of the code  D Inside Null rest of the code Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 25. Handling Exception  Different mechanism.  Simple try - catch  try with multiple catch  multiple exception with single catch  nested try statements  throw  Throws  try, catch and finally (exception with exit code)  Java Exception Propagation 25Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 26. Simple try - catch  The try block allows you to define a block of code to be tested/monitor for errors while it is being executed.  The catch block allows you to define a block of code to be executed, if an error occurs in the try block. 26Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 27. Example 27Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 28. Try with multiple catch  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 28Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 29. Try with multiple catch Ex 29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 30. multiple exception with single catch  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. 30Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 31. multiple exception with single catch Ex 31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 32. multiple exception with single catch Ex 32Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 33. nested try statements  The try statement can be nested.  That is, a try statement can be inside the block of another try.  If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match.  This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted.  If no catch statement matches, then the Java run-time system will handle the exception 33Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 34. nested try statements Ex 34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 35. 35 Poll Question  Which of these is a super class of all errors and exceptions in the Java language?  A RunTimeExceptions  B Throwable  C Catchable  D None of the above Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 36. Handling Exception  Different mechanism.  Simple try - catch  try with multiple catch  multiple exception with single catch  nested try statements  throw  Throws  try, catch and finally (exception with exit code)  Java Exception Propagation 36Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 37. 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.  Syntax:  Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.  The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.  If no matching catch is found, then the default exception handler halts the program and prints the stack trace 37Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 38. throw 38Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 39. 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 types of exceptions that a method might throw.  This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.  If they are not, a compile-time error will result. 39Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 40. Throws  This is the general form of a method declaration that includes a throws clause:  exception-list is a comma-separated list of the exceptions that a method can throw.  First, you need to declare that throwOne( ) throws IllegalAccessException.  Second, main( ) must define a try/catch statement that catches this exception. 40Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 41. Throws 41Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 42. Throws 42Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 43. try, catch and finally  When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method.  This could be a problem in some methods. For example,  if a method opens a file upon entry and closes it upon exit,  then you will not want the code that closes the file to be bypassed by the exception-handling mechanism.  The finally keyword is designed to address this contingency 43Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 44. try, catch and finally  finally creates a block of code that will be executed after a try/catch block has completed and  before the code following the try/catch block.  The finally block will execute whether or not an exception is thrown. 44Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 45. try, catch and finally 45Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 46. Java’s Built-in Exceptions  Inside the standard package java.lang, Java defines several exception classes.  A few have been used by the preceding examples. 46Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 47. Java’s Built-in Exceptions 47Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 48. Java’s Built-in Exceptions 48Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 49. Creating Your Exception Subclasses  Although Java’s built-in exceptions handle most common errors  user 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). class UserException extends Exception { } 49Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 50. Creating Your Exception Subclasses class InvalidMobile extends Exception { InvalidMobile(String msg) { super(msg); } } 50Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 51. Creating Your Exception Subclasses 51Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 52. Creating Your Exception Subclasses 52Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 53. 53 The End… Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam