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

Java - Exception Handling Concepts

  • 1.
    Exception Handling Dr. P.Victer Paul, Indian Institute of Information Technology Kottayam
  • 2.
    2 Why?  Users mayuse 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 inJava  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 inJava  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 ExceptionHandling 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 classWithoutExceptionHandling{ 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 classWithExceptionHandling{ 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  Allexception 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 ClassHierarchy 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  Exceptionis 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 moreclasses 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 moreclasses 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  TheError 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 Severalmore 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  Considerthe 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  Exceptionsfall 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 moreclasses Several more classes Several more classes IllegalArgumentException Unchecked exception. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 22.
    22 what happens whendon’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??  ACompile 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  Differentmechanism.  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. VicterPaul, Indian Institute of Information Technology Kottayam
  • 28.
    Try with multiplecatch  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 multiplecatch Ex 29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 30.
    multiple exception withsingle 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 withsingle catch Ex 31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 32.
    multiple exception withsingle 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 statementsEx 34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 35.
    35 Poll Question  Whichof 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  Differentmechanism.  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. VicterPaul, Indian Institute of Information Technology Kottayam
  • 39.
    Throws  If amethod 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 isthe 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. VicterPaul, Indian Institute of Information Technology Kottayam
  • 42.
    Throws 42Dr. P. VicterPaul, Indian Institute of Information Technology Kottayam
  • 43.
    try, catch andfinally  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 andfinally  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 andfinally 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 ExceptionSubclasses  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 ExceptionSubclasses class InvalidMobile extends Exception { InvalidMobile(String msg) { super(msg); } } 50Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 51.
    Creating Your ExceptionSubclasses 51Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 52.
    Creating Your ExceptionSubclasses 52Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 53.
    53 The End… Dr. P.Victer Paul, Indian Institute of Information Technology Kottayam