Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Throwing and Catching Exceptions

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 26

13

Throwing and Catching Exceptions

Copyright © 2007, Oracle. All rights reserved.


Objectives

After completing this lesson, you should be able to do


the following:
• Explain the basic concepts of exception handling
• Write code to catch and handle exceptions
• Write code to throw exceptions
• Create your own exceptions

13-2 Copyright © 2007, Oracle. All rights reserved.


What Is an Exception?

An exception is an unexpected event.

13-3 Copyright © 2007, Oracle. All rights reserved.


Exception Handling in Java

1. A method throws an exception.


2. A handler catches the exception.

Exception object

Handler
for this
Yes exception? No

13-4 Copyright © 2007, Oracle. All rights reserved.


Advantages of Java Exceptions:
Separating Error-Handling Code

• In traditional programming, error handling often


makes code more confusing to read.
• Java separates the details of handling unexpected
errors from the main work of the program.
• The resulting code is clearer to read and, as a
result, less prone to bugs.

13-5 Copyright © 2007, Oracle. All rights reserved.


13-6 Copyright © 2007, Oracle. All rights reserved.
Advantages of Java Exceptions:
Passing Errors Up the Call Stack

Traditional error Java exceptions


handling
method1 Method1
//handle error Error //handle ex
code
method2 method2
Error Exception
code ex
method3 method3
Error
method4 code method4
Each method checks for method4 throws an
errors and returns an error exception; eventually
code to its calling method. method1 catches it.

13-7 Copyright © 2007, Oracle. All rights reserved.


Advantages of Java Exceptions:
Exceptions Cannot Be Ignored

Traditional error Java exceptions


handling
method1 method1
//handle error //handle ex

method2 method2
Exception
ex
method3 method3
Error
method4 code method4
If method3 ignores the The exception must be
error, it will never be caught and handled
handled. somewhere.

13-8 Copyright © 2007, Oracle. All rights reserved.


Checked Exceptions, Unchecked
Exceptions, and Errors

All errors and exceptions extend the Throwable class.

Throwable

Error Exception

Unrecoverable Checked
RuntimeException
errors exceptions

Unchecked (run-time)
exceptions

13-9 Copyright © 2007, Oracle. All rights reserved.


13-10 Copyright © 2007, Oracle. All rights reserved.
Handling Exceptions

Three choices:
• Catch the exception and handle it.
• Allow the exception to pass to the calling method.
• Catch the exception and throw a different
exception.

13-11 Copyright © 2007, Oracle. All rights reserved.


Catching and Handling Exceptions

• Enclose the method try {


call in a try block. // call the method
• Handle each }
exception in a catch catch (exception1) {
block. // handle exception1
• Perform any final }
processing in a catch (exception2) {
finally block. // handle exception2
}…
finally {
// any final processing
}

13-12 Copyright © 2007, Oracle. All rights reserved.


13-13 Copyright © 2007, Oracle. All rights reserved.
Catching a Single Exception

int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here

13-14 Copyright © 2007, Oracle. All rights reserved.


Catching Multiple Exceptions

try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}

13-15 Copyright © 2007, Oracle. All rights reserved.


Cleaning Up with a finally Block

FileInputStream f = null;
try {
f = new FileInputStream(filePath);
while (f.read() != -1)
charcount++;
}
catch(IOException e) {
System.out.println("Error accessing file " + e);
}
finally {
// This block is always executed
f.close();
}

13-16 Copyright © 2007, Oracle. All rights reserved.


Guided Practice: Catching and
Handling Exceptions
void makeConnection(String url) {
try {
URL u = new URL(url);
}
catch (MalformedURLException e) {
System.out.println("Invalid URL: " + url);
return;
}
finally {
System.out.println("Finally block");
}
System.out.println("Exiting makeConnection");
}

13-17 Copyright © 2007, Oracle. All rights reserved.


Guided Practice: Catching and
Handling Exceptions
void myMethod () {
try {
getSomething();
} catch (IndexOutOfBoundsException e1) {
System.out.println("Caught IOBException ");
} catch (Exception e2) {
System.out.println("Caught Exception ");
} finally {
System.out.println("No more exceptions ");
}
System.out.println("Goodbye");
}

13-18 Copyright © 2007, Oracle. All rights reserved.


Allowing an Exception to Pass to the
Calling Method

• Use throws in the method declaration.


• The exception propagates to the calling method.

public int myMethod() throws exception1 {


// code that might throw exception1
}

public URL changeURL(URL oldURL)


throws MalformedURLException {
return new URL("http://www.oracle.com");
}

13-19 Copyright © 2007, Oracle. All rights reserved.


Throwing Exceptions

• Throw exceptions by using the throw keyword.


• Use throws in the method declaration.

throw new Exception1();

public String getValue(int index) throws


IndexOutOfBoundsException {
if (index < 0 || index >= values.length) {
throw new IndexOutOfBoundsException();
}

}

13-20 Copyright © 2007, Oracle. All rights reserved.


Creating Exceptions

Extend the Exception class:


public class MyException extends Exception { … }

public class UserFileException extends Exception {


public UserFileException (String message) {
super(message);
}
}

13-21 Copyright © 2007, Oracle. All rights reserved.


Catching an Exception and Throwing a
Different Exception

catch (exception1 e) {
throw new exception2(…);
}

void readUserFile() throws UserFileException {


try {
// code to open and read userfile
}
catch(IOException e) {
throw new UserFileException(e.toString());
}
}

13-22 Copyright © 2007, Oracle. All rights reserved.


Summary

In this lesson, you should have learned how to do the


following:
• Use Java exceptions for robust error handling
• Handle exceptions by using try, catch, and
finally
• Use the throw keyword to throw an exception
• Use a method to declare an exception in its
signature to pass it up the call stack

13-23 Copyright © 2007, Oracle. All rights reserved.


Practice 13 Overview:
Throwing and Catching Exceptions

This practice covers the following topics:


• Creating a custom exception
• Changing DataMan finder methods to throw
exceptions
• Handling the exceptions when calling DataMan
finder methods
• Testing the changes to the code

13-24 Copyright © 2007, Oracle. All rights reserved.


13-25 Copyright © 2007, Oracle. All rights reserved.
13-26 Copyright © 2007, Oracle. All rights reserved.

You might also like