Throwing and Catching Exceptions
Throwing and Catching Exceptions
Throwing and Catching Exceptions
Exception object
Handler
for this
Yes exception? No
method2 method2
Exception
ex
method3 method3
Error
method4 code method4
If method3 ignores the The exception must be
error, it will never be caught and handled
handled. somewhere.
Throwable
Error Exception
Unrecoverable Checked
RuntimeException
errors exceptions
Unchecked (run-time)
exceptions
Three choices:
• Catch the exception and handle it.
• Allow the exception to pass to the calling method.
• Catch the exception and throw a different
exception.
int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}
FileInputStream f = null;
try {
f = new FileInputStream(filePath);
while (f.read() != -1)
charcount++;
}
catch(IOException e) {
System.out.println("Error accessing file " + e);
}
finally {
// This block is always executed
f.close();
}
catch (exception1 e) {
throw new exception2(…);
}