Lecture 5
Exceptions
Some slides were borrowed from Josh Hug and Adam Jundt
Reminders
Exceptions
Exceptions
Exceptions
Exceptions
Handling Errors
Sometimes things go wrong, e.g.
The Java approach to handling these exceptional events is to throw an exception.
Exceptions: May be Explicitly or Implicitly Thrown
Java itself can throw exceptions implicitly, e.g.
String t = "Marina";
int n = Integer.parseInt(t);
Exceptions: May be Explicitly or Implicitly Thrown
Java itself can throw exceptions implicitly, e.g.
Java code can also throw exceptions explicitly using throw keyword:
public static void main(String[] args) {
System.out.println("ayyy lmao");
throw new RuntimeException("For no reason.");
}
Creates new object of type RuntimeException!
$ java Alien
ayyy lmao
Exception in thread "main" java.lang.RuntimeException: For no reason.
at Alien.main(Alien.java:4)
String t = "Marina";
int n = Integer.parseInt(t);
Problem
class Exceptions {
static int num = 10;
public static void main(..) {
double result = divideByNumber(0);
}
public static double divideByNumber (int d) {
return num/d;
}
}
try... catch
Solution
class Exceptions {
static int num = 10;
public static void main(..) {
double result = divideByNumber(0);
}
public static double divideByNumber (int d) {
return num/d;
}
}
Solution
class Exceptions {
static int num = 10;
public static void main(..) {
double result = divideByNumber(0);
}
public static double divideByNumber (int d) {
return num/d;
}
}
try... catch again
try {
// code
}
catch(IndexOutOfBounds e) {
// code
}
catch(ArithmeticExpection e) {
// code
}
try_catch and Declaring
exceptions
DEclaring an exception. User’s problem (demo)
Method pop from Java doc
There are two ways to handle exceptions:
Throw and checked exceptions, demo
Throw: Explicitly throw an exception
A: IllegalArgumentException: Too Young
B: IllegalArgumentException: Too Young
Welcome to my party!
C:
IllegalArgumentException: Too Young
Welcome to my party!
IllegalArgumentException: Too Old
D: Something else
Checked Exception
(code will not compile)
Slides were borrowed from Josh Hug
“Must be Caught or Declared to be Thrown”
Occasionally, you’ll find that your code won’t even compile, for the mysterious reason that an exception “must be caught or declared to be thrown”.
public static void main(String[] args) {
Eagle.gulgate();
}
$ javac What.java
What.java:2: error: unreported exception IOException; must be caught or declared to be thrown
Eagle.gulgate();
^
Checked Exceptions
Examples so far have been unchecked exceptions. There are also checked exceptions:
public class Eagle {
public static void gulgate() {
if (today == “Wed”) {
throw new IOException("hi"); }
}
}
To be defined soon...
$ javac Eagle
Eagle.java:4: error: unreported exception IOException; must be caught or declared to be thrown
throw new IOException("hi"); }
^
Unchecked Exceptions
By contrast unchecked exceptions have no such restrictions.
public class UncheckedExceptionDemo {
public static void main(String[] args) {
if (today == “Wed”) {
throw new RuntimeException("as a joke"); }
}
}
$ javac UncheckedExceptionDemo.java
$ java UncheckedExceptionDemo
Exception in thread "main" java.lang.RuntimeException: as a joke.
at UncheckedExceptionDemo.main(UncheckedExceptionDemo.java:3)
Checked vs. Unchecked Exceptions
Any subclass of RuntimeException or Error is unchecked, all other Throwables are checked.
Throwable
Error
Exception
Runtime
Exception
IOException
Midi
Unavailable
Exception
FileNotFound
Exception
IndexOutOf
BoundsException
Assertion
Error
...
unchecked
checked
Checked vs. Unchecked
public class UncheckedExceptionDemo {
public static void main(String[] args) {
if (today == “Wed”) {
throw new RuntimeException("as a joke"); }
}
}
public class Eagle {
public static void gulgate() {
if (today == “Wed”) {
throw new IOException("hi"); }
}
}
Java considers this an “unchecked” exception.
Java considers this a “checked” exception.
Why didn’t you catch or specify??
Checking Exceptions
Compiler requires that all checked exceptions be caught or specified.
Two ways to satisfy compiler:
public static void gulgate() {
try {
if (today == “Wed”) {
throw new IOException("hi"); }
} catch (Exception e) { #is ok
System.out.println("psych!");
}
}
Checking Exceptions
Compiler requires that all checked exceptions be caught or specified.
Two ways to satisfy compiler:
public static void gulgate() throws IOException {
... throw new IOException("hi"); ...
}
Checking Exceptions
If a method uses a ‘dangerous’ method (i.e. might throw a checked exception), it becomes dangerous itself.
$ javac What.java
What.java:2: error: unreported exception IOException; must be caught or declared to be thrown
Eagle.gulgate();
^
How do we fix this?
Catch or specify!
public static void gulgate() throws IOException {
... throw new IOException("hi"); ...
}
public static void main(String[] args) {
Eagle.gulgate();
}
Checking Exceptions
Two ways to satisfy compiler: Catch or specify exception.
Specify that you might throw an exception.
Use when someone else should handle.
public static void gulgate() throws IOException {
... throw new IOException("hi"); ...
}
public static void main(String[] args) {
try {
Eagle.gulgate();
} catch(IOException e) {
System.out.println("Averted!");
}
}
Catch an Exception:
Keeps it from getting out.
Use when you can handle the problem.
public static void main(String[] args)
throws IOException {
Eagle.gulgate();
}
Throws vs throw
public int pop() throws EmptyStackException {� int obj;�� if (size == 0) {� throw new EmptyStackException();� }�� obj = objectAt(size - 1);� setObjectAt(size - 1, null);� size--;� return obj;�}
Not checked, so
public int pop() throws EmptyStackException {� int obj;�� if (size == 0) {� throw new EmptyStackException();� }�� obj = objectAt(size - 1);� setObjectAt(size - 1, null);� size--;� return obj;�}
https://beginnersbook.com/2013/04/difference-between-throw-and-throws-in-java/
Why Exceptions?
Allows you to keep error handling code separate from ‘real’ code.
func readFile: {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
what if the file doesn’t exist?
what if there’s not enough memory?
what happens if reading fails?
Error Handling Code (Naive)
One naive approach to the right.
func readFile: {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
func readFile: {
open the file;
if (theFileIsOpen) {
determine its size;
if (gotTheFileLength) {
allocate that much memory;
} else {
return error("fileLengthError");
}
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
return error("readError");
}
...
} else {
return error("memoryError");
}
} else {
return error("fileOpenError")
}
}
With Exceptions
func readFile: {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (sizeDeterminationFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
func readFile: {
open the file;
if (theFileIsOpen) {
determine its size;
if (gotTheFileLength) {
allocate that much memory;
} else {
return error("fileLengthError");
}
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
return error("readError");
}
...
} else {
return error("memoryError");
}
} else {
return error("fileOpenError")
}
}