catch (Exception e)
Download
Report
Transcript catch (Exception e)
Introduction to Exceptions in
Java
CS201, SW Development Methods
Failures at run-time
• Divide by zero? Try to access an object
reference that’s null?
– Your program halts
– It prints the location of where it failed
• You might think this is “built-in” as part of
how Java runs a program
• But Java gives you the same ability to
recognize error or situations and respond
however you want to
When Things Go Wrong
• Java uses exceptions. When something “goes
wrong” at a line of code:
– An exception object gets created
– Flow of control changes to some place in your code
that can handle the exception
• Note: usually changes in flow-of-control are
clearly marked by Java keywords
– return, if/else, while, for, switch, call to a method,
break, continue
– Exceptions and a “jump” to somewhere else can
occur where it’s not so obvious
What We Need to Know
• We need to understand
– What an exception object is and what we might do
with it.
– How to manage the flow-of-control when an exception
occurs
• Can we ignore exceptions? Some of them:
– Unchecked exceptions: serious system problems, the
program fails, you normally don’t try to handle these
– Checked exceptions: Java requires you to do
something with these. Either:
• Handle them when they occur
• Declare that you are passing responsibility back up to the
method that called your code
Exception class hierarchy
• Java developers create a new exception class
for each “type” of exception that can occur. A
few examples:
– NullPointerException: attempt to access an object
reference that is null
– IOException: some sort of I/O problem has occurred
– FileNotFoundException: failed to open a file
• Each one its own class, all derived from the
Exception superclass
– You can easily create your own exceptions by
extending Exception (but we won’t today)
Superclass of
all Errors and
Exceptions
We could catch this or
any of its subclasses
Problems we
must catch
Serious
problems you
shouldn’t try to
worry about!
How to Use an Exception Object
• Something bad has happened, and you
have access to the exception object.
What methods can you call on it?
– String getMessage()
• Each exception encapsulates a text-message that
says what the problem is
– void printStackTrace()
• You’ve see this! It’s a list of the methods called
that led to this exception, with the class and line
numbers.
Control Flow and Exceptions
• Java lets you surround code that might generate
an exception…
– Called a “try block”
• And attach handlers that will take care of
problems if they occur in this block
– Called “catch blocks”
• Java also lets you do something else:
– Declare that your method will pass any exception
back up to it’s caller
– We’ll explain later
try/catch/finally
try {
// lines of code that
// might throw exceptions
}
catch ( ExceptionType1 e) {
// handle 1st type of exceptions
}
catch ( ExceptionType2 e) {
// handle 2nd type of exceptions
}
finally {
// code executed in all cases
}
If some code in here throws
an exception, then an
exception object is created
and we jump to the first catch
block.
Can have 1 or more catchblocks. The first one where
the thrown exception object
matches the “parameter
type” is executed.
If we need to make sure
something is always done
after try-block and/or catchblock, it goes here
Comments on try/catch/finally
• try block
– Any variable declared here is local to the try-block
– Often, declare and initialize outside the try-block, then
change it inside the block.
• catch blocks
– Often there’s just one kind of exception that can
happen.
– If more than one possible
• Often we test for specific types of exceptions first
• Then have catch (Exception e) which will capture any other
kind of exception since they all match the super-class type
Comments on try/catch/finally
• finally block
– Always executed!
• whether or not an exception is thrown
• even if the try or catch blocks execute a return
– Useful for closing files, freeing resources like
database connections, etc.
What to Do in a Catch Block?
• You can do anything to try to recover from the
problem
– Ask for new input, use a different value, whatever
makes sense
– Print more useful information
• Remember getMessage() and printStackTrackTrace() can be
called on the exception object
– (To be explained later) You can throw the same
exception which passes it back to the caller
Advice on Writing Exception
Handling Code
• Empty catch blocks are used to ignore
exceptions
– Don’t do this unless it makes sense for your
code!
• Keep it simple: wrap as few lines as
possible in a try-block
• Recognize you can’t always safely recover
– Sometimes best to “die gracefully”