Exceptions and Assertions
Chapter 15 – CSCI 1302
CSCI 1302 – Exceptions and Assertions 2
Outline
• Introduction• Exceptions and Exception Types
– Exception Classes– Checked and Unchecked Exceptions
• Understanding Exception Handling– Declaring Exceptions– Throwing Exceptions– Catching Exceptions
• Rethrowing Exceptions
CSCI 1302 – Exceptions and Assertions 3
Outline
• The finally clause• When to Use Exceptions• Creating Custom Exception Classes• Assertions
– Declaring Assertions– Running Programs with Assertions– Using Exception Handling or Assertions
CSCI 1302 – Exceptions and Assertions 4
Introduction
• Three types of errors:– Syntax errors– Runtime errors– Logic errors
• Exception handling deals with runtime errors
• Assertions promote program correctness
CSCI 1302 – Exceptions and Assertions 5
Exceptions and Exception Types
• Events that occur during the execution of a program and disrupt the normal flow of control
• Abnormal termination can lead to many serious issues
• Exceptions occur whenever Java detects a runtime error
• Unlike events, exceptions cannot be ignored
• Java provides exception handling
CSCI 1302 – Exceptions and Assertions 6
Exceptions and Exception Types
• Consider a program that only takes integer input
• Typically, entering anything other than an integer will cause the program to terminate abnormally (See Test.java)
• Using a try-catch block, we can detect this and respond to it (See TestException.java, TestExceptionRobust.java)
CSCI 1302 – Exceptions and Assertions 7
Exception Classes
CSCI 1302 – Exceptions and Assertions 8
Exception Classes
• All exceptions are instances of a class derived from Throwable
• Three major types of exceptions:– System errors – Internal system errors
thrown by JVM, very rare– Exceptions – Errors caused by your
program and external circumstances– Runtime exceptions – Programming
errors
CSCI 1302 – Exceptions and Assertions 9
Checked/Unchecked Exceptions
• RuntimeException, Error, and their subclasses are unchecked exceptions
• All others are checked, meaning the compiler forces the programmer to check for them and deal with them
• Typically, an unchecked exception is an indication of a programming logic error
• These can occur anywhere, which is why Java doesn’t force you to check them
CSCI 1302 – Exceptions and Assertions 10
Understanding Exception Handling
• The exception handling model is based on three items– Declaring an exception– Throwing an exception– Catching an exception
CSCI 1302 – Exceptions and Assertions 11
Declaring Exceptions
• Every method must state the types of checked exceptions it might throw
• To declare an exception, a method should use the throws keywordpublic void rfile() throws IOException
• Methods can throw multiple exceptionspublic void rfile() throws IOException, IllegalArgumentException, Exception3, Exception4
CSCI 1302 – Exceptions and Assertions 12
Throwing Exceptions
• Create an instance of the appropriate exception and throw itIllegalArgumentException ex = new IllegalArgumentException(“Wrong Argument”);
throw ex;
• or as an alternativethrow new IllegalArgumentException(“Wrong Argument”);
CSCI 1302 – Exceptions and Assertions 13
Catching Exceptions
• If no exceptions occur during a try-catch block, the catch blocks are not executed
• Once an exception occurs, the remaining lines of code in the try block are ignored and control goes to the catch blocks
• The exception handler is the code that handles the particular exception
CSCI 1302 – Exceptions and Assertions 14
Catching Exceptions
• Java looks through the catch blocks from first to last
• If no handler is found, the exception is passed to the invoking method
• If no handler is found after moving all the way up the invocation chain, an error is printed to the console
• Catching an exception describes this process of finding a handler
CSCI 1302 – Exceptions and Assertions 15
Catching Exceptions
• See text on pg. 555
main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } statement2; }
method1 { ... try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; } statement4; }
method2 { ... try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; } statement6; }
An exception is thrown in method3
CSCI 1302 – Exceptions and Assertions 16
Catching Exceptions
• If a handler is found, the exception object is assigned to that variable
• These objects contain useful information that can be retrieved– getMessage() – Detailed message– toString() –Full name of exception
class: getMessage()– printStackTrace() – Throwable object
and stack info• See TestCircleWithException.java
CSCI 1302 – Exceptions and Assertions 17
Catching Exceptions
• Methods are executed on threads• Exceptions terminate the thread they
are being run on• GUI applications use many threads
while running• Can throw an exception and not
terminate• See IntegerDivision.java• See IntegerDivisionException.java
CSCI 1302 – Exceptions and Assertions 18
Rethrowing Exceptions
• Exceptions can be rethrown to allow any necessary actions to be completed
try {statements;
} catch (Exception ex) { pre-exit operations; throw ex;}
CSCI 1302 – Exceptions and Assertions 19
The finally Clause
• The finally clause is code executed regardless of an exception occurring or nottry {statements;
} catch (Exception ex) {handle ex;
} finally { final statements;}
• See pg. 561 for examples
CSCI 1302 – Exceptions and Assertions 20
When to use Exceptions
• Exception handling provides a robust solution to handle errors
• Using it can be expensive however, it instantiates new objects, rolls back the call stack, and sometimes has to travel the chain of invoking methods
• If an exception can be handled inside a method, there is no reason to throw it
• If an error occurs in multiple places, consider creating an exception class
CSCI 1302 – Exceptions and Assertions 21
When to Use Exceptions
• Simple errors in individual methods shouldn’t be handled with exceptions
• Try-catch blocks should be used to handle unexpected error conditions
try {System.out.println(rVar);
} catch (NullPointerException ex) { System.out.println(“rVar is null”);}
CSCI 1302 – Exceptions and Assertions 22
When to Use Exceptions
• The previous code should be replaced with something similar to:
if (rVar != null) System.out.println(rVar);
else System.out.println(“rVar is null”);
CSCI 1302 – Exceptions and Assertions 23
Custom Exception Classes
• Java provides many exception classes that should be used whenever possible
• Occasionally, you will need to create an exception that cannot be handled by the built-in exception classes
• Create your own class and have it descend from Exception or any of its subclasses
• See RadiusException.java and CircleWithException2.java
CSCI 1302 – Exceptions and Assertions 24
Assertions
• A Java statements that enables you to assert an assumption about your program
• Contains a Boolean expression that should be true during execution
• Used to ensure program correctness and avoid logic errors
CSCI 1302 – Exceptions and Assertions 25
Declaring Assertions
• Use the keyword assertassert assertion;
orassert assertion: detailedMessage;
• If an assertion is false, an AssertionError is thrown, the program displays a message on the console and exits
• See AssertionDemo.java
CSCI 1302 – Exceptions and Assertions 26
Running Programs with Assertions
• By default, assertions are disabled at runtime
• Enable them with the –enableassertions or –ea switch on the command linejava –ea AssertionDemo
CSCI 1302 – Exceptions and Assertions 27
Exception Handling or Assertions
• Assertions address correctness• Exceptions address robustness• Assertions should not be used to
replace exceptions• Do not use assertions for argument
checking in public methods• Use assertions to reaffirm assumptions
– Good example of this is in a switch statement with no default case
CSCI 1302 – Exceptions and Assertions 28
Exception Handling or Assertions
• Good use for an assertion:
switch (month) {case 1: … ; break;case 2: … ; break;…case 12: …; break;default: assert false: “Invalid month: “ + month;
}