Download presentation
Presentation is loading. Please wait.
Published byJewel Jefferson Modified over 9 years ago
1
Exceptions and Assertions Chapter 15 – CSCI 1302
2
CSCI 1302 – Exceptions and Assertions2 Outline Introduction Exceptions and Exception Types –Exception Classes –Checked and Unchecked Exceptions Understanding Exception Handling –Declaring Exceptions –Throwing Exceptions –Catching Exceptions Rethrowing Exceptions
3
CSCI 1302 – Exceptions and Assertions3 Outline The finally clause When to Use Exceptions Creating Custom Exception Classes Assertions –Declaring Assertions –Running Programs with Assertions –Using Exception Handling or Assertions
4
CSCI 1302 – Exceptions and Assertions4 Introduction Three types of errors: –Syntax errors –Runtime errors –Logic errors Exception handling deals with runtime errors Assertions promote program correctness
5
CSCI 1302 – Exceptions and Assertions5 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
6
CSCI 1302 – Exceptions and Assertions6 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 )
7
CSCI 1302 – Exceptions and Assertions7 Exception Classes
8
CSCI 1302 – Exceptions and Assertions8 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
9
CSCI 1302 – Exceptions and Assertions9 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
10
CSCI 1302 – Exceptions and Assertions10 Understanding Exception Handling The exception handling model is based on three items –Declaring an exception –Throwing an exception –Catching an exception
11
CSCI 1302 – Exceptions and Assertions11 Declaring Exceptions Every method must state the types of checked exceptions it might throw To declare an exception, a method should use the throws keyword public void rfile() throws IOException Methods can throw multiple exceptions public void rfile() throws IOException, IllegalArgumentException, Exception3, Exception4
12
CSCI 1302 – Exceptions and Assertions12 Throwing Exceptions Create an instance of the appropriate exception and throw it IllegalArgumentException ex = new IllegalArgumentException(“Wrong Argument”); throw ex; or as an alternative throw new IllegalArgumentException(“Wrong Argument”);
13
CSCI 1302 – Exceptions and Assertions13 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
14
CSCI 1302 – Exceptions and Assertions14 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
15
CSCI 1302 – Exceptions and Assertions15 Catching Exceptions See text on pg. 555
16
CSCI 1302 – Exceptions and Assertions16 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
17
CSCI 1302 – Exceptions and Assertions17 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
18
CSCI 1302 – Exceptions and Assertions18 Rethrowing Exceptions Exceptions can be rethrown to allow any necessary actions to be completed try { statements; } catch (Exception ex) { pre-exit operations; throw ex; }
19
CSCI 1302 – Exceptions and Assertions19 The finally Clause The finally clause is code executed regardless of an exception occurring or not try { statements; } catch (Exception ex) { handle ex; } finally { final statements; } See pg. 561 for examples
20
CSCI 1302 – Exceptions and Assertions20 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
21
CSCI 1302 – Exceptions and Assertions21 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”); }
22
CSCI 1302 – Exceptions and Assertions22 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”);
23
CSCI 1302 – Exceptions and Assertions23 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
24
CSCI 1302 – Exceptions and Assertions24 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
25
CSCI 1302 – Exceptions and Assertions25 Declaring Assertions Use the keyword assert assert assertion; or assert assertion: detailedMessage; If an assertion is false, an AssertionError is thrown, the program displays a message on the console and exits See AssertionDemo.java
26
CSCI 1302 – Exceptions and Assertions26 Running Programs with Assertions By default, assertions are disabled at runtime Enable them with the –enableassertions or –ea switch on the command line java –ea AssertionDemo
27
CSCI 1302 – Exceptions and Assertions27 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
28
CSCI 1302 – Exceptions and Assertions28 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; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.