Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Lecture 15 Exception Handling

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture 15 Exception Handling

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Maharaja Agrasen Institute of Technology

CIC-212 Java Programming

Exception Handling
Errors and Exceptions
The objectives of this chapter are:

 To understand the exception handling


mechanism defined in Java
 To explain the difference between errors
and exceptions
 To show the use and syntax of exceptions
 To describe how to create your own
exception classes.
Traditional Methods of Handling Errors
 In most procedural languages, the standard way of indicating an
error condition is by returning an error code.

 The calling code typically did one of the following:


 Testing the error code and taking the appropriate action.
 Ignoring the error code.

 It was considered good programming practice to only have one


entry point and one exit point from any given function.
 This often lead to very convoluted code.
 If an error occurred early in a function, the error condition
would have to be carried through the entire function to be
returned at the end. This usually involved a lot of if
statements and usually lead to gratuitously complex code.
Syntax Errors, Runtime Errors, and
Logic Errors
You learned that there are three categories of errors:
Syntax errors, Runtime errors, and Logic errors.
Syntax errors arise because the rules of the language
have not been followed. They are detected by the
compiler.
Runtime errors occur while the program is running if
the environment detects an operation that is
impossible to carry out.
Logic errors occur when a program doesn't perform
the way it was intended to.
Error handling through Exceptions
 Gradually, programmers began to realize that the
traditional method of handling errors was too
cumbersome for most error handling situations.
 This gave rise to the Exception concept
 When an error occurs, that represents an Exceptional
condition.
 Exceptions cause the current program flow to be
interrupted and transferred to a registered exception
handling block.
 This might involve unrolling the method calling stack.

 Exception handling involves a well-structured goto.


Exception -Terminology
 When an error is detected, an exception is thrown.
 Any exception which is thrown, must be caught by and
exception handler
 If the programmer hasn't provided one, the exception will be caught by
a catch-all exception handler provided by the system.
 The default exception handler may terminate the application.

 Exceptions can be rethrown if the exception cannot be


handled by the block which caught the exception
 Java has 5 keywords for exception handling:
try
catch
finally
throw
throws
Exceptional flow of control
Exceptions break the normal flow of
control.
When an exception occurs, the statement
that would normally execute next is not
executed.
What happens instead depends on:
whether the exception is caught,
where it is caught,
what statements are executed in the ‘catch
block’,
and whether you have a ‘finally block’.
Runtime Errors

1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
Catch Runtime Errors
1 import java.util.*;
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 } while (continueInput);
25 }
13 }
Approaches to handling an exception
1. Prevent the exception from happening.
2. Catch it in the method in which it occurs, and either
a. Fix up the problem and resume normal execution.
b. Rethrow it.
c. Throw a different exception.
3. Declare that the method throws the exception.
4. With 1. and 2.a. the caller never knows there was an
error.
5. With 2.b., 2.c., and 3., if the caller does not handle the
exception, the program will terminate and display a
stack trace.
Exceptions -Syntax
try
{
// Code which might throw an exception
// ...
}
catch(FileNotFoundException x)
{
// code to handle a FileNotFound exception
}
catch(IOException x)
{
// code to handle any other I/O exceptions
}
catch(Exception x)
{
// Code to catch any other type of exception
}
finally
{
// This code is ALWAYS executed whether an exception was thrown
// or not. A good place to put clean-up code. ie. close
// any open files, etc...
}
Execution of try catch blocks
• For normal execution:
• try block executes, then finally block executes, then other
statements execute
• When an error is caught and the catch block throws an exception
or returns:
• try block is interrupted
• catch block executes (until throw or return statement)
• finally block executes
• When error is caught and catch block doesn’t throw an exception
or return:
• try block is interrupted
• catch block executes
• finally block executes
• other statements execute
• When an error occurs that is not caught:
• try block is interrupted
• finally block executes
Sequence of Events for throw

Preceding step

try block

throw
statement

unmatched catch

matching catch

unmatched catch

next step
Sequence of Events for No throw

Preceding step

try block

throw
statement

unmatched catch

matching catch

unmatched catch

next step
Sequence of Events for finally clause
Preceding step

try block

throw
statement

unmatched catch

matching catch

unmatched catch

finally

next step
Exception Handler

Exception
"thrown" here
Thrown
Thrownexception
exceptionmatched
matchedagainst
against
first
firstset
setofofexception
exceptionhandlers
handlers
Exception
handler
IfIfititfails
failsto
tomatch,
match,ititisismatched
matchedagainst
against
next
nextset
setofofhandlers,
handlers,etc.
etc.
Exception
handler

IfIfexception
exceptionmatches
matchesnone
noneofofhandlers,
handlers,
program
programisisabandoned
abandoned
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution

The final block is


try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution

Next statement in the


try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution

try { Suppose an exception


statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution

try { The exception is


statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution

try { The final block is


statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution

try { The next statement in


statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
Declaring, Throwing, and Catching
Exceptions

method1() { declare exception


method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}
Declaring Exceptions

Every method must state the types of checked exceptions


it might throw. This is known as declaring exceptions.

public void myMethod() throws IOException

public void myMethod() throws IOException,

OtherException
Automatically Passing Exceptions
If your method is defined to throw an exception, you need not
catch it within your method

public void addURL(String urlText) throws MalformedURLException


{
URL aURL = new URL(urlText);

// if the above throws a MalformedURLException, we need not have


// a try/catch block here because the method is defined to
// throw that exception. Any method calling this method MUST
// have a try/catch block which catches MalformedURLExceptions.
// Control is automatically transferred to that catch block.

}
Using throws clause
If you don’t want the exception to be handled in the same function you can use the
throws class to handle the exception in the calling function.
public class myexception{
public static void main(String args[])
{ In this example, the main
try{ method calls the
checkEx(); checkEx() method and the
} catch(FileNotFoundException ex){ } checkEx method tries to
open a file, If the file in not
} available, then an
public void checkEx() throws FileNotFoundException exception is raised and
{ passed to the main
File f = new File(“myfile”); method, where it is
handled.
FileInputStream fis = new
FileInputStream(f);
//continue processing here.
}
}
Exceptions -throwing multiple exceptions
 A Method can throw multiple exceptions.
 Multiple exceptions are separated by commas after the throws
keyword: public class MyClass
{
public int computeFileSize() throws IOException, ArithmeticException
[...]

public void method1()


{
MyClass anObject = new MyClass();
try
{
int theSize = anObject.computeFileSize();
}
catch(ArithmeticException x)
{
// ...
}
catch(IOException x)
{
// ...
Exception -The catch-all Handler
 Since all Exception classes are a subclass of the Exception class, a
catch handler which catches "Exception" will catch all exceptions.
 It must be the last in the catch List

public void method1()


{
FileInputStream aFile;
try
{
aFile = new FileInputStream(...);
int aChar = aFile.read();
//...
}
catch(IOException x)
{
// ...
}
catch(Exception x)
{
// Catch All Exceptions
The finally block
public void method1()
{
FileInputStream aFile;
try
{
aFile = new FileInputStream(...);
int aChar = aFile.read();
//...
}
catch(IOException x)
{
// ...
}
catch(Exception x)
{
// Catch All other Exceptions
}
finally
{
try
{
aFile.close();
}
catch (IOException x)
{
// close might throw an exception
}
}
Throwing Exceptions Example

/** Set a new radius */


public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Throwing Exceptions
 You can throw exceptions from your own methods.

 To throw an exception, create an instance of the exception class


and "throw" it.
 If you throw checked exceptions, you must indicate which
exceptions your method throws by using the throws keyword

public void withdraw(float anAmount) throws InsufficientFundsException


{
if (anAmount<0.0)
throw new IllegalArgumentException("Cannot withdraw negative
amt");

if (anAmount>balance)
throw new InsuffientFundsException("Not enough cash");

balance = balance - anAmount;


}
Re-throwing Exceptions
 If you catch an exception but the code determines it cannot
reasonably handle the exception, it can be rethrown:

public void addURL(String urlText) throws MalformedURLException


{
try
{
URL aURL = new URL(urlText);
// ...
}
catch(MalformedURLException x)
{
// determine that the exception cannot be handled here
throw x;
}
}
When to Throw Exceptions

An exception occurs in a method. If you want


the exception to be processed by its caller, you
should create an exception object and throw
it.
If you can handle the exception in the method
where it occurs, there is no need to throw it.
Catching Exceptions

main method { method1 { method2 { An exception


... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
Exception Classes
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


System Errors
ClassNotFoundException

IOException
ArithmeticException
System errors Exception areAWTException
thrown by JVM and represented in
the Error class. The ErrorNullPointerException class describes internal
RuntimeException
system errors. Such errors rarely occur. If one does,
IndexOutOfBoundsException
Object there
Throwable is little you Several
canmoredo classes beyond notifying the user and
IllegalArgumentException
trying to terminate the program gracefully.
LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError

ExceptionErrordescribes errors caused by your program


and external circumstances.
AWTError
These errors can be
caught and handled byclassesyour program.
Several more
Runtime Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
RuntimeException
Error is caused by programming errors,
such as bad AWTError
casting, accessing an out-of-bounds array,
and numericSeveral
errors.
more classes
Checked Exceptions vs. Unchecked
Exceptions

RuntimeException, Error and their


subclasses are known as unchecked
exceptions. All other exceptions are
known as checked exceptions, meaning
that the compiler forces the programmer
to check and deal with the exceptions.
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).

void p1() { void p1() throws IOException {


try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}

(a) (b)
Unchecked Exceptions

In most cases, unchecked exceptions reflect programming


logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to
it; an IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array.
These are the logic errors that should be corrected in the
program. Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-catch
blocks, Java does not mandate you to write code to catch
unchecked exceptions.
Checked or Unchecked Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError Unchecked
exception.
Several more classes
Cautions When Using Exceptions

Exception handling separates error-handling code


from normal programming tasks, thus making
programs easier to read and to modify. Be aware,
however, that exception handling usually requires
more time and resources because it requires
instantiating a new exception object, rolling back
the call stack, and propagating the errors to the
calling methods.
Creating Custom Exception Classes

 Use the exception classes in the API


whenever possible.
 Create custom exception classes if the
predefined classes are not sufficient.
 Declare custom exception classes by
extending Exception or a subclass of
Exception.
class TestException
Example { public static void main(String[] args)
{ int x=5, y=1000;
try
{ float z=(float)x/(float)y;
class Myexception extends Exception if (z < 0.01)
{ throw new Myexception (“Number
is too small”);
Myexception(String msg)
}
{
catch (Myexception e)
super(msg);
{ S.O.P(“caught my exception”);
}
S.O.P(e.getMessage());
}
}
finally { S.O.P(“I am always here”);} }
}
50
Summary
Exception
Indication of problem during execution
Uses of exception handling
Process exceptions from program components
Handle exceptions in a uniform manner in large projects
Remove error-handling code from “main line” of
execution
A method detects an error and throws an
exception
Exception handler processes the error
Uncaught exceptions yield adverse effects
Might terminate program execution

You might also like