Software Engineering I SENG201
Lecture 15 – Exceptions in Java March 23, 2022
Copyright By PowCoder代写 加微信 powcoder
Previous lecture
1. How do identify test cases
2. Unit testing with JUnit
1. Introduction
2. Throwing and catching exceptions
3. Types of exceptions
4. Writing your own exception
1. Introduction
2. Throwing and catching exceptions
3. Types of exceptions
4. Writing your own exception
What is an “exception” in Java?
Exception: Undesired event that occurs during execution of program that disrupts normal flow of program
Exception in Java: Language-provided mechanisms to handle these undesired events
Exceptions are not Java-specific; also supported in other languages.
Undesired events during execution – examples
• Reference to null pointer
• Out-of-bounds arrays
• Division by zero
• Attempt to open a non-existent file
• Attempt to access non-existent network connection
• When an error is detected at runtime, an exception is thrown
• Code that caused exception stops immediately
• Control of program is transferred to somewhere else – E.g.,othercodethatdealswithexception
Call stack (method calls)
Call stack (exception throws)
Method 3 (exception occurred)
Throws exception
Forwards exception
Deals with exception
Looking for handler
Looking for handler
Method 2 (without exception handler)
Method 1 (with exception handler)
Benefits of exceptions
• Separation of “error handling code” from “regular” code
– What to do when something goes wrong separated from main logic
– Avoids spaghetti code
• Propagation of errors up the call stack
– Deal with problem at the most appropriate place
– Only methods who care about errors have to deal with it
1. Introduction
2. Throwing and catching exceptions
3. Types of exceptions
4. Writing your own exception
Throw in method (create exception)
• Illustrative example only
– There are potentially more elegant ways to address issue in code
public class BankAccount {
private double balance;
public BankAccount(double aBalance) { balance = aBalance; }
public void withdraw(double amount) {
if(amount > balance) {
throw new IllegalArgumentException(“amount > balance”); balance = balance – amount;
System.out.println(“You just withdrew ” + amount + “ RMB.”);
public static void main(String[] argv) {
BankAccount myAccount = new BankAccount(50); myAccount.withdraw(100);
Most exception objects can be constructed with an error message
Creates and throws object of type
IllegalArgumentException
Not executed when exception is thrown
Exception in thread “main” java.lang.IllegalArgumentException: amount > balance at BankAccount.withdraw(BankAccount.java:8)
at BankAccount.main(BankAccount.java:15)
IllegalArgumentException in API
Catching exceptions
• Previous example does not explicitly catch exception – IllegalArgumentException is “unchecked” exception
• To explicitly catch
– Surround code that can throw exceptions with try/catch
– At least one catch in a try block to catch one or more exceptions
– Specifies actions to take when one or more exceptions occur
• Basic exception handling
– Print state info for debugging + terminate (gracefully)
– Exceptions in Java are objects (i.e., can use methods)
• printStackTrace(), toString(), etc. to provide details
// Some code
catch(ExceptionOne e1) {
// handler to deal with ExceptionOne
// do something to process exception
catch(ExceptionTwo e2) {
Exception is created somewhere below here in call stack
// handler to deal with ExceptionTwo
// do something to process this other exception
Java tries to match it with one of these
We caught an IllegalArgumentException! java.lang.IllegalArgumentException: amount > balance amount > balance java.lang.IllegalArgumentException: amount > balance
at lecture15.BankAccount.withdraw(BankAccount.java:36) at lecture15.BankAccount.main(BankAccount.java:76)
public class BankAccount { …
public void withdraw(double amount) {
if(amount > balance) {
throw new IllegalArgumentException(“amount > balance”); balance = balance – amount;
public static void main(String[] args) {
BankAccount myAccount = new BankAccount(50); try
myAccount.withdraw(100); catch (IllegalArgumentException e)
// process e
System.out.println(“We caught an IllegalArgumentException!”); System.out.println(e.toString()); System.out.println(e.getMessage());
e.printStackTrace();
Example – throwing existing exceptions
import java.io.*; import java.util.*;
public class DataReader {
public void getData(String fileName) {
First, this is executed
// throws NullPointerException if fileName is null
File f = new File(fileName);
// might throw FileNotFoundException Scanner s = new Scanner(f);
catch(NullPointerException npe) {
System.err.println(“Terminating: null fileName”);
catch(FileNotFoundException fnfe) {
fnfe.printStackTrace(); System.err.println(“Please check spelling”); System.exit(42);
If match is found, run corresponding code
Exception object visible to that code
How do we know thrown exceptions?
Class File in Java API
How do we know thrown exceptions?
Class Scanner in Java API
Clean-up with finally
• May need to take action whether or not exception is thrown – Zero or one finally in try block
– E.g.,toclosefileafterwriting
– Called when try block is complete
– In either case (exception or not)
public void writeList(ArrayList
PrintWriter out = null;
out = new PrintWriter(new FileWriter(“OutFile.txt”)); for (int i = 0; i < v.size(); i++)
out.println("Value " + i + " = " + v.get(i));
catch(ArrayIndexOutOfBoundsException e) {
System.err.println("ArrayIndexOutOfBounds: " + e.getMessage());
catch(IOException e) {
System.err.println("Bad IO: " + e.getMessage());
if(out != null)
System.out.println("Closing PrintWriter");
out.close();
System.out.println("PrintWriter not open");
Let a method throw exception
Method terminates when exception occurs
throws clause lists thrown exceptions
import java.io.*; ...
public void getData(String fileName) throws FileNotFoundException {
// throws NullPointerException if fileName is null
File f = new File(fileName);
// throws FileNotFoundException if f does not exist Scanner s = new Scanner(f);
Caller of getData can handle exception (try-catch block) or throw it further (using throws)
Throw exceptions further
public class BankAccount {
public void withdraw(double amount) throws IOException {
if(amount > balance)
throw new IOException (“amount > balance”); balance = balance – amount;
public void withdrawWithPenalty(double amount) throws IOException {
double amountWithPenalty = (0.1 * amount) + amount; withdraw(amountWithPenality);
public static void main(String[] args)
BankAccount myAccount = new BankAccount(50);
myAccount.withdrawWithPenality(100); catch (IOException) // process e
System.out.println(“We caught an IOException!”); System.out.println(e.toString()); System.out.println(e.getMessage()); e.printStackTrace();
withdraw()
(may throw IOException; throws IOException to caller)
withdrawWithPenalty() (throws IOException to caller)
main() (catches IOException)
1. Introduction
2. Throwing and catching exceptions
3. Types of exceptions
4. Writing your own exception
Two types of exceptions
• Checked exceptions
• Unchecked exceptions
Checked exceptions
• Due to circumstances that programmer cannot prevent – Intrinsically difficult kind of error
• Always include code that acknowledges exception is thrown
– Declared in method header using a throws clause, or
– Put code that may cause exception inside a try block with catch
• Examples
– Subclasses of java.io.IOException
Unchecked exception
• Often indicate programming errors
– Someone needs to manually fix the code
– Exceptions that “should not happen”
– E.g., out of memory, resource seems to disappear, etc.
• Compiler allows us to ignore them if we wish
– Can be caught in a try block
– If not, need not be listed in method’s throws clause
• Examples
– NullPointerException
– IllegalArgumentException
Exceptions in the object hierarchy
Object Throwable
Superclass of all errors and exceptions in Java
RuntimeException
IOException
1. Introduction
2. Throwing and catching exceptions
3. Types of exceptions
4. Writing your own exception
Write your own exception
• Exceptions are classes
• May design own exception class
– If we need exception type not in the Java API
– If we cannot access someone else’s exceptions
– If code throws more than one related exception
• Must all be subclasses of Throwable – Partofclasshierarchy
// BankAccount
public void withdraw(double amount)…
if(amount > balance) {
throw new InsufficientFundsException(“amount > balance”);
public class InsufficientFundsException extends IllegalArgumentException {
public InsufficientFundsException(){}
public InsufficientFundsException(String message)
// Other methods
super(message);
1. Introduction
2. Throwing and catching exceptions
3. Types of exceptions
4. Writing your own exception
Cartoon of the day
Key lesson: We cannot fully avoid bugs. Therefore, exceptions help us handle runtime problems.
“If debugging is the process of removing software bugs, then programming must be the process of putting them in.” (Edsger Dijkstra)
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com