Intermezzo: Java Error Handling - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

Intermezzo: Java Error Handling

Description:

A program may crash during execution because of: trouble reading data, ... Separates the error handling code from your regular code, thereby keeping things neater ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 35
Provided by: watt50
Category:

less

Transcript and Presenter's Notes

Title: Intermezzo: Java Error Handling


1
Intermezzo Java Error Handling
Slides from Katleen Cristie
2
Introduction
  • PROBLEM
  • A program may crash during execution because of
    trouble reading data,
  • illegal characters in the data,
  • an out of bounds array index
  • a file not being present or being in a different
    location etc.
  • SOLUTION
  • Java Errors and Exceptions enable the programmer
    to deal with such problems. You can write a
    program that recovers from errors and keeps on
    running.

3
Introduction
  • So far we have written our code with the
    assumption that nothing ever goes wrong
  • BUT this is unrealistic.
  • The reality is that unexpected situations can
    arise and interfere with the intended
    functioning of software
  • Java provides an exception handling facility

4
Pre-defined Exception Classes
  • An exception is an event that occurs, during the
    life of a program, that could cause that program
    to behave unreliably
  • ExampleAccessing an array with an invalid index

Charatan Kans, Java in Two Semesters, p347
5
Exceptional Event
  • Exception is short for exceptional event
  • DefinitionAn exception is an event that occurs
    during the execution of a program that disrupts
    the normal flow of instructions
  • Exceptions can range fromserious problems e.g.
    hard disk crashes to a simple programming mistake
    such as trying to access an element in an array
    that does not exist.

6
Exceptional Event
  • Whenever an exception occurs in a Java method,
    the method creates an exception object and hands
    it to the runtime system
  • The exception object contains information about
  • the type of exception
  • where the exception occurred
  • and so forth
  • After an exception occurs, the runtime system
    looks for some code to handle the exception if
    none is found, then the application will terminate

7
The Advantage Of Exceptions
  • Separates the error handling code from your
    regular code, thereby keeping things neater
  • Error types can be grouped there are
    identifiable types of errors that are likely to
    occur
  • Errors may be handled at specific locations in
    the code (and not necessarily where the error
    occurred)

8
Runtime Exceptions
  • Some instructions can fail at runtime
  • If they fail they can throw an exception
  • Exceptions can happen at any time in the
    execution of an application
  • They interrupt the execution of the application
  • Exceptions are used to report errors
  • Exceptions can be caught

9
Vulnerable Situations
  • Javas exception handling facility provides a
    powerful way to safely handle dangerous events
    such as our array example
  • Most events that can lead to an exception are
    already known to the Java system and, thus, are
    catered for
  • This means the programmer is freed from the need
    to write the code that identifies an occurrence
    of the event and, instead, can focus on writing
    the code that deals with the event

10
Generic Code
  • try
  • // statements
  • catch (exceptionType name)
  • // statements
  • finally
  • // statements

11
Exception Structure
  • Try statementIdentifies a block of statements
    within which an exception might be thrown
  • In plain English try doing this see if it
    works if it doesnt, then were ready for it!

12
Exception Structure
  • Catch statementMust be used with a try
    statement is used to identify a block of
    statements that handles a particular type of
    exception
  • Whenever an exception occurs, the code contained
    within this block of statements will be performed
  • In plain EnglishSo it stuffed up were still
    ready for it so lets deal with it

13
Exception Structure
  • Finally statementMust be associated with the
    try statement
  • Identifies a block of statements that are
    executed regardless of whether or not an
    exception occurs within the try block
  • For example, irrespective of whether things
    worked or not, lets just clean up the mess left
    before moving on to the next part of the program

14
Using the Keyword Finally
  • Consider the code that will be placed within your
    finally block
  • Dont put code within a catch block that should
    really be in a finally block i.e. closing a file.
    Why? Well if the specific error for that catch
    block did occur then yes, the file would be
    closed
  • But what if a different error occurred? The file
    would never be closed which is obviously not a
    good example of tidy programming!

15
Using the Keyword Finally
  • Lets assume that, irrespective of the type of
    error that occurs, we want to make sure that the
    file is closed
  • Do we close the file in all of our catch blocks?
    Or, do we (considerably more sensibly) use the
    code in our finally block
  • Because, at the end of the day, even if an error
    does not occur, we still need to close the file!

16
Exception Types
  • There are many, many different types of
    exception
  • These exceptions can be classed as checked
    exceptions and unchecked exceptions
  • Unchecked exceptions are runtime exceptions i.e.
    a null pointer exception, an arithmetic exception
    etc
  • These runtime exceptions can occur anywhere in
    the program and, thus, to try and catch all of
    these potential exceptions would be a nightmare
    job code everywhere and so forth

17
Exception Types
  • Thus, Java does not make you catch all of these
    potential exceptions there would just be too
    many try-catch statements
  • And therefore, we class these as unchecked they
    go unchecked by the Java compiler
  • On the other hand we have checked exceptions
  • When you compile your program, the Java compiler
    checks to ensure that you have added sufficient
    code to catch these exceptions and if you
    have not done this, then the compiler refuses to
    compile the code

18
More On Exceptions
  • The first step to catching an exception is to
    define the try block the try block should be
    used wherever there is a vulnerable piece of
    codeThe try block essentially defines the scope
    of the exceptionNote that you must then follow
    this with a catch and finally block of code
    which defines what happens should an exception
    occur.

try // statements
19
More On Exceptions
  • The catch statementNote that you can have
    multiple catch statements following a try block
    to cater for different types of exceptions that
    could occurFor example, we may know that doing
    process x may result in the throwing of an
    exception of type a, and/or the throwing of an
    exception of type b etc.

catch // statements catch //
statements
20
Example
  • The following example illustrates this point more
    fully

try // statements Catch (ArrayIndexOutOfBoun
dsException Error) // statements Catch
(IOException Error) // statements
As can be seen, the code anticipates 2 different
exception types
21
More On Exceptions
  • Within the exceptions class you can access
    methods to obtain the type of exception that
    occurredAfter all, remember that it is an
    exception object that is created when an
    exception occurs and, thus, there are various
    methods that are available for objects of this
    type

ArrayIndexOutOfBoundsException Error System.out.p
rintln(Error.getMessage())
22
More On Exceptions
  • The statement shown below would catch only errors
    of type ArrayIndexOutOfBoundsExceptionIt would
    not catch our other previous example, the
    IOException

try // statements Catch (ArrayIndexOutOfBoun
dsException Error) // statements
23
General Exception Handlers
  • However, it is possible to catch exceptions with
    both specific exception handlers and general
    exception handlers
  • The use of general exception handlers obviously
    gives less specific handling for the type of
    exception but can be used to keep things simpler
  • All exceptions inherit from the Throwable class
    this is the class at the top of the exceptions
    hierarchy

24
Exception ObjectsThrowing an Exception
  • Each piece of code that could lead to an
    exception is associated with a pre-defined
    exception class
  • The class has been named to reflect the nature
    of the exception
  • When a given event occurs, the Java runtime
    environment determines which exception has
    occurred and an object of the given exception
    class is generated
  • This process is known as throwing an exception

i.e. ArrayIndexOutOfBoundsException class
25
The Throwable Class
  • All exception classes inherit from the base class
    Throwable which is found in the java.lang
    package
  • Throwable has two immediate subclasses
  • Exception
  • Error

26
Examples
  • FileNotFoundException the expected file has not
    been found
  • EOFException the end of the file has been
    reachedBoth of the above are examples of
  • IOException Input/Output exceptions
  • Thus, we have subclasses that are categorized
    depending upon the type of the exception
  • The two initially mentioned examples reside in
    the java.io package (input/output)

27
The Error Class
  • The Error class
  • describes internal system errors that are very
    unlikely to occur i.e. VirtualMachineError, where
    an error in the Java Virtual Machine has been
    detected
  • When an error such as this occurs, there is
    really not all that much that can be done other
    than to crash as gracefully as possible!

28
The Exception Class
  • All other exceptions are subclasses of the
    Exception class and it is these exceptions that
    we can take account of within our own programs
  • Important sub-divisions in the Exception class
  • IOException and RuntimeException
  • RuntimeException deals with program errors that
    arise when executing a program i.e.
    ArrayIndexOutOfBoundsException (attempting to
    access an array with an illegal
    index)NumberFormatException(attempting to
    convert a String to an int)

29
IOException Class
  • IOException class deals with external errors that
    could affect the program during periods of input
    and or output
  • i.e. corruption of an external file

30
Unchecked Exceptions
  • Just about any Java instruction has the potential
    to end in a RuntimeException error
  • Thus, the Java compiler does not insist that all
    of these potential exceptions are dealt with by
    the programmer
  • Whether they are checked or not up to the
    individual programmer
  • Thus known as unchecked exceptions

31
Checked Exceptions
  • Since a programmer cannot control IOException
    errors, the Java compiler insists that
    programmers deal with such errors when statements
    that could result in such errors are used
  • These kinds of errors are thus known as
  • checked exceptions

32
Custom Exceptions
You can create your own exception
types Typically, you will subclass from the
Exception class As a rule, always place the word
exception within the name of your class
33
Class ExceptionTest
As can be seen, when the testInt method is
invoked and a parameter outwith the range 0 to 5
is provided, then a new NumberOutOfRangeException
object is created, and the input that was
provided is passed to this new object as a
parameter
public class ExceptionTest public
ExceptionTest() // do nothing
public void testInt(int input) throws Exception
if(input lt 0 input gt 5)
throw new NumberOutOfRangeException(input)
else System.out.println("You
input " input)
34
Class NumberOutOfRangeException
public class NumberOutOfRangeException extends
Exception public NumberOutOfRangeException(int
number) super("The number " number "
is out of range")
The NumberOutOfRangeException class, as defined
to suit a particular programmers needs Note
that it extends Exception
Custom exceptions as you can see, specific to
the programmers needs with some additional info
being passed up
  • Running this
Write a Comment
User Comments (0)
About PowerShow.com