0% found this document useful (0 votes)
38 views

Exception Handling in Java

The document discusses exception handling in Java. It defines errors and exceptions, and describes traditional error handling approaches used in other languages like C. It then explains that exceptions provide a better approach to error handling in Java. Exceptions represent error conditions and are thrown and handled using try-catch blocks. Checked exceptions must be caught or declared, while unchecked exceptions terminate the program. The document provides examples and discusses how to declare and handle exceptions in Java code.

Uploaded by

xhienye
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Exception Handling in Java

The document discusses exception handling in Java. It defines errors and exceptions, and describes traditional error handling approaches used in other languages like C. It then explains that exceptions provide a better approach to error handling in Java. Exceptions represent error conditions and are thrown and handled using try-catch blocks. Checked exceptions must be caught or declared, while unchecked exceptions terminate the program. The document provides examples and discusses how to declare and handle exceptions in Java code.

Uploaded by

xhienye
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

Exception Handling in

Java

1
Introduction
 Users have high expectations
for the code we produce.
 Users will use our programs
in unexpected ways.
 Due to design errors or
coding errors, our programs
may fail in unexpected ways
during execution

2
Introduction
 It is our responsibility to
produce quality code that
does not fail unexpectedly.
 Consequently, we must
design error handling into our
programs.

3
Errors and Error
Handling
 An Error is any unexpected result
obtained from a program during
execution.
 Unhandled errors may manifest
themselves as incorrect results or
behavior, or as abnormal program
termination.
 Errors should be handled by the
programmer, to prevent them
from reaching the user.

4
Errors and Error
Handling
 Some typical causes of errors:
 Memory errors (i.e. memory
incorrectly allocated, memory
leaks, “null pointer”)
 File system errors (i.e. disk is
full, disk has been removed)
 Network errors (i.e. network is
down, URL does not exist)
 Calculation errors (i.e. divide by
0)

5
Errors and Error
Handling
 More typical causes of errors:
 Array errors (i.e. accessing
element –1)
 Conversion errors (i.e. convert
‘q’ to a number)
 Can you think of some others?

6
Errors and Error
Handling
 Traditional Error Handling
 1. Every method returns a value
(flag) indicating either success,
failure, or some error condition. The
calling method checks the return flag
and takes appropriate action.
 Downside: programmer must
remember to always check the return
value and take appropriate action.
This requires much code (methods
are harder to read) and something
may get overlooked.

7
Errors and Error
Handling
 Traditional Error Handling
 Where used: traditional
programming languages (i.e. C)
use this method for almost all
library functions (i.e. fopen()
returns a valid file or else null)

8
Errors and Error
Handling
 Traditional Error Handling
 2. Create a global error handling
routine, and use some form of
“jump” instruction to call this routine
when an error occurs.
 Downside: “jump” instruction (GoTo)
are considered “bad programming
practice” and are discouraged. Once
you jump to the error routine, you
cannot return to the point of origin
and so must (probably) exit the
program.

9
Errors and Error
Handling
 Traditional Error Handling
 Where used: many older
programming texts (C,
FORTRAN) recommended this
method to programmers. Those
who use this method will
frequently adapt it to new
languages (C++, Java).

10
Errors and Error
Handling
 Exceptions – a better error handling
 Exceptions are a mechanism that
provides the best of both worlds.
 Exceptions act similar to method return
flags in that any method may raise and
exception should it encounter an error.
 Exceptions act like global error methods
in that the exception mechanism is built
into Java; exceptions are handled at
many levels in a program, locally and/or
globally.

11
Exceptions
Definition & Some Postulates
An exception is an event that occurs during the
execution of a program that disrupts the normal
flow of instructions (error). (Sun tutorial:
Handling Errors with Exceptions)

 When an error occurs within a method, the


method creates an object and hands it to the
runtime system. The object, called an exception
object, contains information about the error.

 Exceptions provide a clean way to check for


errors - by using exceptions you handle
errors and still have clear, readable code.

12
Exceptions
 What are they?
 An exception is a representation
of an error condition or a
situation that is not the
expected result of a method.
 Exceptions are built into the
Java language and are available
to all program code.
 Exceptions isolate the code that
deals with the error condition
from regular program logic.

13
Exceptions
 How are they used?
 Exceptions fall into two categories:
 Checked Exceptions
 Unchecked Exceptions
 Checked exceptions are inherited
from the core Java class Exception.
They represent exceptions that are
frequently considered “non fatal” to
program execution
 Checked exceptions must be handled
in your code, or passed to parent
classes for handling.

14
Exceptions
 How are they used?
 Unchecked exceptions
represent error conditions that
are considered “fatal” to
program execution.
 You do not have to do anything
with an unchecked exception.
Your program will terminate
with an appropriate error
message.

15
Exceptions
 Examples:
 Checked exceptions include
errors such as “array index out
of bounds”, “file not found” and
“number format conversion”.
 Unchecked exceptions include
errors such as “null pointer”.

16
Exceptions
 How do you handle exceptions?
 Exception handling is accomplished
through the “try – catch”
mechanism, or by a “throws”
clause in the method declaration.
 For any code that throws a checked
exception, you can decide to
handle the exception yourself, or
pass the exception “up the chain”
(to a parent class).

17
Exceptions
 How do you handle exceptions?
 To handle the exception, you write a
“try-catch” block. To pass the
exception “up the chain”, you declare
a throws clause in your method or
class declaration.
 If the method contains code that may
cause a checked exception, you
MUST handle the exception OR pass
the exception to the parent class
(remember, every class has Object as
the ultimate parent)

18
Exceptions
:: Definition & Some Postulates
 Exceptions are an explicit part of methods’
behaviour.
 Exceptions are thrown at runtime if errors
occur when a class is loaded or during method
execution.
 How does the JVM handle the errors in a in a
nested chain of function calls?

19
Exceptions
:: Exception Postulates
 Runtime exceptions are objects of the classes
java.lang.Exception, java.lang.Error or their
subclasses. All of them implement the interface
java.lang.Throwable.
 Runtime exceptions are also called unchecked
exceptions.
 Code may also throw an exception using the
throw statement. Such an exception is a non-
runtime or checked exception.

20
Exceptions
Exception Postulates
 Both forms of exceptions (checked and
unchecked) may be caught and handled in
exception-handling code.
 An uncaught exception is caught by a default

handler which halts execution and displays an


error message.
 Exception handling is done using the try-catch-

finally statment.
The Error class descendants indicate serious problems that
The Error class descendants indicate serious problems that
a reasonable application should not try to catch. Most such
errors are abnormal conditions.
A method is not required to throw any subclasses of Error.

21
Exceptions
:: Exception Handling
What to do if there is an erroneous (vulnerable)
piece or code? Let’s say this piece of code is the
function f(). With exceptions, all you have to do is
to:
 put the call to f() in a try-catch block;

 make provisions for handling the error in the

catch block such as in the following example.

try {
f();
}
catch (MyException e) {
System.out.println(e);
};

22
Exceptions
:: Exception Handling
try {
f();
}
catch (MyException e) {
System.out.println(e);
};

In f(), if the erroneous conditions are met, all you


have to do is to raise an exception in f() - throw
MyException exception.

throw new MyException(“Error description


here”);

23
Exceptions
:: Exception Handling – The Block try-catch-finally
The block try-catch-finally:
 Must include either one catch clause or a finally

clause.
 Can has multiple catch clauses but only one

finally clause.
 A catch clause can handle only one exception

type.
 The finally clause depicts block of code that

must always be executed when the try block is


exited, no matter how the try block is exited.
 The try statements are executed until an
exception is thrown or it completes successfully.

24
Exceptions
:: Exception Handling – The Block try-catch-finally

 If an exception is thrown, each catch clause


is inspected in turn for a type to which the
exception can be assigned; be sure to order
them from most specific to least specific.
 When a match is found, the exception object
is assigned to the identifier and the catch
statements are executed.
 If no matching catch clause is found, the
exception percolates up to any outer try
block that may handle it.
 A catch clause may throw another
exception.
 If a finally clause is included, it's statements
are executed after all other try-catch
processing is complete. 25
Exceptions
:: Throwing Exceptions

 Methods can throw exceptions explicitly, using


the throw statement.
 Methods must declare in their throws clause,
which checked exceptions they may throw.
public void myMethod(Params)
throws Exception1, Exception2
{

switch (i) {
case 0: throw new Exception1();
case 1: throw new Exception2();
}
}

26
Exceptions
:: Throwing Exceptions

 In the throws clause, you do not


have to include any checked
exception, which will be caught
and handled within the method.

 A method can throw multiple


exceptions.

 A method can only throw


exceptions that have been declared
in its throws clause.

27
Exceptions
:: Creating Exceptions

To create your own exception class, you must inherit


from an existing exception class. The simplest way to
create a new exception is to let the compiler create the
constructor (by default) for you:
class MyException extends Exception {}

Example:
public class MyExceptionTest {
public void f() throws MyException {

throw new MyException();
}
public static void main(String[] args) {
MyExceptionTest oTest = new MyExceptionTest ();
try { oTest.f(); }
catch(MyException e)
{ System.err.println("Caught it!"); }
}
}
28
Coding Exceptions
 Try-Catch Mechanism
 Wherever your code may
trigger an exception, the
normal code logic is placed
inside a block of code starting
with the “try” keyword:
 After the try block, the code to
handle the exception should it
arise is placed in a block of
code starting with the “catch”
keyword.

29
Coding Exceptions
 Try-Catch Mechanism
 You may also write an optional
“finally” block. This block contains
code that is ALWAYS executed,
either after the “try” block code,
or after the “catch” block code.
 Finally blocks can be used for
operations that must happen no
matter what (i.e. cleanup
operations such as closing a file)

30
Coding Exceptions
 Example
 try {
… normal program code
}
catch(Exception e) {
… exception handling code
}

31
Coding Exceptions
 Passing the exception
 In any method that might throw
an exception, you may declare
the method as “throws” that
exception, and thus avoid
handling the exception yourself
 Example
 public void myMethod throws
IOException {
… normal code with some I/O
}

32
Coding Exceptions
 Types of Exceptions
 All checked exceptions have class
“Exception” as the parent class.
 You can use the actual exception
class or the parent class when
referring to an exception
 Where do you find the exception
classes?
 Reference books such as “Java in a
Nutshell” (O’Reilly, 2001), or the Java
Documentation.

33
Coding Exceptions
 Types of Exceptions
 Examples:
 public void myMethod throws
Exception {
 public void myMethod throws
IOException {
 try { … }
catch (Exception e) { … }
 try { … }
catch (IOException ioe) { … }

34
Exceptions
:: Exception Handling – The Block try-catch-finally
Example:
class VirtualPerson {
public void drinkCoffee(CoffeeCup cup) {
try {
int i = (int) (Math.random() * 4.0);
switch (i) {
case 0: throw new TooHotException();
case 1: throw new
TooColdException();
case 2: throw new
UnusualTasteException();
default: System.out.println("This
coffee is great!");
}
}
catch (TooHotException e) {
System.out.println("This coffee is too hot.");
}
catch (TooColdException e) {
System.out.println("This coffee is too cold.");
}
catch (UnusualTasteException e) {
System.out.println("This coffee is too strong.");
}
finally {
System.out.println("Can I please have another
cup?");
}
}
}

35
Summary
 Exceptions are a powerful error
handling mechanism.
 Exceptions in Java are built into
the language.
 Exceptions can be handled by
the programmer (try-catch), or
handled by the Java
environment (throws).

36

You might also like