Exceptions and Exception Handling - PowerPoint PPT Presentation

1 / 15
About This Presentation
Title:

Exceptions and Exception Handling

Description:

Throwable Exceptions can be caught and handled ... arises in the try block, control switches to the corresponding catch block ... The exception is caught ... – PowerPoint PPT presentation

Number of Views:133
Avg rating:3.0/5.0
Slides: 16
Provided by: foxr
Category:

less

Transcript and Presenter's Notes

Title: Exceptions and Exception Handling


1
Exceptions and Exception Handling
  • Exceptions arise when an erroneous situation is
    faced during the execution of the program
  • In most cases, an exception causes a run-time
    error and thus the (abnormal) termination of your
    program
  • The error is accompanied by an output to
    System.out that states where and what the
    exception was
  • Exception Handling is a mechanism whereby you can
    try to catch exceptions and handle them so that
    your program does not terminate
  • There are 3 ways to handle exceptions
  • Do not handle it, let the situation terminate
    your program
  • Handle the exception where it occurs
  • Throw the exception to be handled somewhere else

2
Types of Exceptions
  • In Java, all Exceptions are objects
  • Java designates exceptions as either Error or
    Throwable
  • Throwable Exceptions can be caught and handled
  • Errors cannot and result in program termination
    no matter what
  • Throwable Exceptions are divided into
  • RuntimeException such as
  • ArithmeticException
  • IndexOutofBoundsException
  • NullPointerException
  • OutOfMemoryException
  • ArrayIndexOutOfBoundsException
  • The other class of Exception is Others,
    exceptions which would be syntax errors but are
    not caught at compile time, these include
  • IllegalAccessException
  • NoSuchMethodException
  • ClassNotFoundException

3
Try-Catch-Finally Statements
  • In order to handle an Exception where it occurs
  • place the code that might raise an exception in a
    try block
  • following the try block by one or more optional
    catch blocks
  • If an exception arises in the try block, control
    switches to the corresponding catch block
  • We can also include a finally block
  • This code is executed no matter what, whether an
    exception is raised or not (the finally block is
    optional)
  • A try block can have several catch blocks, where
    each catch is used to catch a different type of
    error
  • a finally block is executed no matter which catch
    block executes and executes even if no catch
    block executes

4
Example
  • Exceptions often arise because the user inputs an
    incorrect value
  • The following example protects against division
    by 0 errors

try System.out.print("Enter an int
value, I will find the reciprocal ")
int num Integer.parseInt(key.readLine( ))
double reciprocal (double) 1 / num
catch (Exception ex)
System.out.println(" Numerical error, cannot
divide by 0 ") reciprocal 0
finally System.out.println("R
eciprocal is " reciprocal)
5
Another Example
  • Here, we input into an array what if the array
    becomes full? Java throws an ArrayIndexOutOfBound
    sException and we catch it and handle it

try int a new int100
int n 0 System.out.print("Enter a
positive int value, -1 to quit ")
int temp Integer.parseInt(key.readLine( ))
while(temp 0) an
temp System.out.print("Enter the next positive
value, -1 to quit ") temp
Integer.parseInt(key.readLine( ))
catch(Exception ex)
System.out.println("Array full! ")
n 99
6
Types of Exceptions
  • Notice in our prior two examples, we only had 1
    catch and we assumed that the exception would be
  • divide by 0 (for the first example)
  • array out of bounds (for the second example)
  • What if a different exception arose?
  • We can specify a more particular type of
    Exception as the parameter
  • In fact, we must specify a particular type if we
    are going to have more than one catch clause
  • We need to specify the type of Exception if we
    plan on having multiple catch statements
  • We could have two catch blocks, one to catch an
    ArrayOutOfBoundsException and another catch an
    ArithmeticException but we have to specify which
    type of Exception each catch block will catch

7
Two Exception Example
  • Consider the loop
  • for(j0j
  • Two exceptions might arise, ArithmeticException
    and ArrayIndexOutofBoundsException
  • The code below will catch either error
    appropriately

try for(j0jbj catch (ArithmeticException ex)
catch (ArrayIndexOutofBoundsException ex)
finally
8
What Should Our Catch Block Do?
  • Just using a try-catch block doesnt necessarily
    solve our problem
  • Our catch block should try to resolve the problem
  • If the array has become full, increase its size
    or tell the user that they cant add any more
  • If an ArithmeticException, then set the variable
    to 0 or try to do a different arithmetic
    operation
  • for instance, if you are trying to take the
    square root and its a negative, then take the
    square root of the absolute value)
  • Or, to be helpful to the programmer who might be
    debugging the program, you could generate the
    stack trace
  • The stack trace is the list of suspended methods
    plus the active method so that you can see where
    the Exception arose
  • Pass your Exception the printStackTrace( )
    message to output the stack trace

9
Another Example
  • The try block below could generate numerous
    exceptions
  • NullPointerException array a wasnt
    instantiated
  • ArrayOutOfBoundsException x is beyond the legal
    bounds of a
  • FileNotFound the file filename does not exist
    or could not be accessed
  • Notice in this case, we change our input to be
    from the keyboard instead!
  • NumberFormatException the item read from the
    file could not be parsed as an int

try BufferedReader infile new
BufferedReader(new FileReader(filename))
ax Integer.parseInt(infile.readLine(
)) catch (NullPointerException
exception) System.out.println(Array not
instantiated) catch (ArrayOutOfBoundsExceptio
n exception) System.out.println (Array full,
cannot add) catch (FileNotFoundException
exception) infile new BufferedReader(new
InputStreamReader(System.in))
System.out.println(file not found, please enter
data from keyboard) catch (NumberFormatExcepti
on exception) ax 0 finally
infile.close( ) // close the infile when
all done with input
10
What If No try-catch Block?
  • Note that code which might raise an exception
    does not need to be placed in a try-catch block
  • If not, the exception is propagated to whatever
    method invoked the given method
  • If the methods call was itself placed in a
    try-catch block, the exception is caught there
  • Propagation continues until either
  • The exception is caught
  • There are no more calling methods, in which case
    the program terminates with an error message
    indicating the run-time stacks trace of method
    calls

11
public class PropagationExample public
static void main(String args)
System.out.println(at main) level1(
) System.out.println(ending main)
public static void level1( )
System.out.println(at level 1)
try level2( )
catch(ArithmeticExce
ption ex)
System.out.println(AE at level 1)
ex.printStackTrace( )
System.out.println(ending level 1)
public static void level2( )
System.out.println(at level 2) level3(
) System.out.println(ending level 2)

Example Catching Somewhere Else
public static void level3( )
System.out.println(at level 3) int
result 5 / 0 System.out.println(endin
g level 3)
Output at main at level 1 at level 2
at level 3 AE at level 1 followed by
the stack trace ending level 1 ending main
12
Explicitly Throwing an Exception
  • Try-catch blocks can be tedious because you may
    want to supply a catch block for every possible
    exception
  • Another approach is to search for a condition
    that would cause an exception and explicitly
    throw that exception
  • If an exception is thrown, it is either caught by
    an exception handler elsewhere, or not
  • In either way, the program will terminate and the
    message from the thrown exception will be
    displayed for the programmer to see in order to
    help debug the error
  • Throwing an exception uses the throw instruction

13
Examples
  • Consider that you want to throw an exception if a
    user enters a test score that is not within the
    range of 0 100
  • if (value 100) throw new
    Exception(Users input value out of
    range)
  • Here, we attempt to place a new value into an
    array a at location x, but first check to make
    sure that x is a legal array subscript
  • if(x a.length) throw new
    Exception(Array index x out of bounds)
    else ax value

14
Checked Exceptions
  • There are some Exceptions that must be checked
    and thrown/caught, these are known as Checked
    Exceptions
  • If you use a class that contains Checked
    Exceptions and you do not try to handle that
    exception, you will get a syntax error
  • All IO classes have Checked Exceptions
  • Therefore, if you use, say BufferedReader, and do
    not try to handle the Exception, you get a syntax
    error when compiling your program
  • NOTE so far, we have merely thrown any
    IOException to the next level (which ultimately
    means that our programs terminate if an
    IOException is raised)
  • We could instead place our code in a try-catch
    block an example follows
  • Most Exceptions are Unchecked, in which case we
    dont have to worry about trying to catch or
    throw them
  • at least we dont have to worry about the
    compiler giving us a syntax error, its still good
    practice to catch Exceptions

15
Example
  • Many of the java.io. classes explicitly check
    for an IOException
  • Our code must handle it, either by adding throws
    IOException to your methods header
  • Or, you can place your code in a try-catch block

try BufferedReader keyboard
new BufferedReader (new InputStreamReader(System.
in)) String x keyboard.readLine(
) catch (IOException exception)
try place all code that does input here
catch(IOException ex)
Write a Comment
User Comments (0)
About PowerShow.com