1 of 15

Exceptions and Exception Handling

CS 240 – Advanced Programming Concepts

2 of 15

Exceptions Overview

  • Abnormal conditions that can occur in a Java class
  • May be but are not necessarily errors
  • Allow you to separate normal processing logic from abnormal processing logic
  • Represented by classes and objects in Java

2

3 of 15

Separation of Normal and Abnormal Processing Logic

public class FileReadingWithoutExceptions {�

public boolean readFile(String fileName, String fileContents) {� boolean success = true;�� File file = new File(filename);�� if(!file.exists()) {� success = false;� }�� if(success) {� fileContents = "<Insert code to read the

file here>";�� if(fileContents == "") {� success = false;� }� }�� return success;� }�}

public class FileReadingWithExceptions {

� public String readFile(String fileName) throws IOException {� File file = new File(fileName);� String fileContents = "<Insert code to read the

file here>";� return fileContents;� }�}

3

4 of 15

Partial Exception Class Hierarchy

4

5 of 15

Try / Catch Blocks

5

Syntax

try {

// Code that may throw an exception

} catch(SomeExceptionType ex) {

// Code to handle the exception

} catch(OtherExceptionType ex) {

// Code to handle the exception

}

Catching but not actually resolving an exception is sometimes called “swallowing” an exception and is a bad practice.

public class TryCatchExample {� public String readFile(String fileName) {� File file = new File(fileName);� String fileContents = "";�� try {� FileReader fr = new FileReader(file);� BufferedReader br = new BufferedReader(fr);�� String line;� while((line = br.readLine()) != null) {� fileContents += line;� fileContents += "\n";� }�� return fileContents;�� } catch(IOException ex) {� ex.printStackTrace();� return fileContents;� }� }�}

6 of 15

Multi-Catch

6

Without Multi-Catch

try {

// Code that may throw an exception

} catch(SomeExceptionType ex) {

// Code to handle the exception

} catch(OtherExceptionType ex) {

// Code to handle the exception

}

With Multi-Catch (added in version 7)

try {

// Code that may throw an exception

} catch(SomeExceptionType | OtherExeptionType ex) {

// Code to handle the exception

}

7 of 15

Checked Exceptions

7

8 of 15

The Handle or Declare Rule

  • Applies to Checked Exceptions (Exceptions that are not RuntimeExceptions)
  • Does not apply to Errors
  • Does not apply to RuntimeExceptions

8

Handle

try {

} catch(Exception ex) {

}

or

Declare

public void method throws Exception {

}

9 of 15

Finally Blocks

  • Always executed
    • Whether an exception occurs or not
    • Whether a catch block exists or not
    • Whether a method is terminated because of an exception or not
  • Normally used to clean up resources (i.e. close files, connections, etc.)

  • Example:
    • FinallyExample.java

9

10 of 15

Try with Resources

public class TryWithResourcesExample {�� public String readFile(String fileName) throws IOException {� File file = new File(fileName);� String fileContents = "";�� try(FileReader fr = new FileReader(file);� BufferedReader br = new BufferedReader(fr)) {� � String line;� while((line = br.readLine()) != null) {� fileContents += line;� fileContents += "\n";� }�� return fileContents;� }� }�}

10

11 of 15

Throwing an Exception

public class ExceptionThrowingExample {�� public void myMethod(int methodParam) {� if(methodParam < 0) {� throw new IllegalArgumentException("The parameter may not be negative");� }� }�}

11

12 of 15

Rethrowing an Exception

public class ExceptionRethrowingExample {�� public void myMethod() {� try {� // Code that may throw different types of exceptions� } catch (RuntimeException ex) {� throw ex;� } catch (Exception ex) {� // Do something with all checked exceptions� }� }�}

12

Avoid swallowing RuntimeExceptions

13 of 15

The Overridden Method Exception Rule

  • Overriding methods can not throw checked exceptions that are not expected by callers of the overridden method
  • Overriding methods can throw:
    • Fewer exceptions than the overridden method
    • The same exceptions as the overridden method
    • Subclasses of exceptions thrown by the overridden method
    • RuntimeExceptions and any RuntimeException subclasses
    • Errors and any Error subclasses
  • Overriding methods can not throw:
    • Anything else (checked exceptions that are not subclasses of exceptions thrown by the overridden method)

13

14 of 15

Creating Your Own Exception Classes

public class ImageEditorException extends Exception {� public ImageEditorException() {� }�� public ImageEditorException(String message) {� super(message);� }�� public ImageEditorException(String message, Throwable cause) {� super(message, cause);� }�� public ImageEditorException(Throwable cause) {� super(cause);� }�}�

14

15 of 15

Citations

1. Diagrams created by course author, Jerod Wilkerson.