Exceptions
Nicholas Duchon: Jun 14, 2019
|
Key Concepts:
|
Introduction
Exceptions? Here is a quick introduction to the key points.
- Exceptions may be thrown by methods.
- Exception classes hierarchy:
- The predefined hierarchy of classes under Throwable - see
the following for a summary:
- Child classes of Error and RuntimeException are
unchecked, all others are checked.
- Checked means the compiler will enforce explicit
handling either in a try/catch block or by rethrowing the
exception.
- A programmer may add an exception class as one would add
any other class to the predefined hierarchy.
- As with all classes, one should be careful to extend the
appropriate class.
- There are two basic pieces of information in the
exception: its class and a String.
- The latter is some kind of message that might/should be
helpful to the user of the method (the programmer) or
perhaps even the end user of the program.
- Instantiating exceptions
- Since they are objects, they are new'ed as any other
object, typically in response to a method detecting
something going very wrong, such as divide by zero or file
not found, which the method is not built to handle. The
method's solution is to send a message to the caller of the
method indicating the failure (the class of the exception)
and something about the nature of the failure (the
exception's String description).
- Throwing an exception
- The code is very simple:
throw new MyException ("I am having a problem");
- The declaration of a method throwing an exception must
explicitly say that it can throw this class of exceptions by
saying:
throws MyException.
This tells the compiler that any method that calls this
method will have to handle this exception explicitly if the
exception is checked (see above).
- Handling an exception
- NEVER: code should never just catch an exception and
ignore it:
- always say or do something sensible,
- if nothing else, print a message to the user/developer
that something went wrong.
- Testing: the test plan should include testing that
exceptions are thrown and handled per specification.
- Let's say method myA() calls myB(), and myB() throws some
exception. Here are the cases:
- The exception is unchecked -
- in which case mA() MAY handle the exception in a
try/catch block.
- The exception is checked - so two cases:
- myA() handles the exception by rethrowing it, so the
problem is escalated, and if no program code handles it,
the JVM will crash gracefully
- myA() handles the exception in a try/catch block -
end of story
- Methods in the Throwable class:
- getMessage () - the String used in the original throw
- getStackTrace () - an array of StackTraceElement
- printStackTrace ([PrintStream | PrintWriter]) - no
parameter prints to console
- toString () - typically more information than getMessage
()
- Examples:
Catching div by 0:
public class
DivZeroTest {
public static void main (String [] args) {
try {
int k = 1, j = 0;
System.out.println ("Div: " +
k/j);
} catch (ArithmeticException e) {
System.out.println ("Exception:
" + e);
System.out.println ("\n*****
e.getMessage ():");
System.out.println ("Exception:
" + e.getMessage());
System.out.println ("\n*****
Thread.dumpStack ():");
Thread.dumpStack ();
System.out.println ("\n*****
e.printStackTrace ():");
e.printStackTrace ();
} // end try/catch
} // end main
} // end class DivZeroTest
Output:
Exception:
java.lang.ArithmeticException: / by zero
***** e.getMessage ():
Exception: / by zero
***** Thread.dumpStack ():
java.lang.Exception: Stack trace
at
java.lang.Thread.dumpStack(Thread.java:1329)
at DivZeroTest.main(DivZeroTest.java:11)
***** e.printStackTrace ():
java.lang.ArithmeticException: / by zero
at DivZeroTest.main(DivZeroTest.java:5)
GUI:
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.");
Unchecked Exception
- This is an example of creating an unchecked exception - new
RuntimeException.
- Note that the message string (cyan) is generated as part of
the new operation.
public class
Exceptions0b {
static void methodA () {
try {
methodB();
} catch
(java.lang.RuntimeException e) {
System.out.println (e.toString());
} // end try/catch
}
// end methodA
static void methodB () {
throw new
java.lang.RuntimeException ("This one is not checked");
}
// end methodB
public static void main (String [] args) {
methodA ();
}
// end main
} //
end class Excaptions 0b
Checked Exception
- This is an exmple of creating a checked exception.
- Note that here, the method throwing the exception, methodB,
MUST explicitly say it is throwing that exception.
- Also, the method calling that method, methodA, MUST handle the
exception one way or another.
public class
Exceptions0a {
static void methodA () {
try {
methodB();
} catch (java.lang.Exception e)
{
System.out.println (e.toString());
} // end try/catch
} // end methodA
static void methodB () throws
java.lang.Exception {
throw new java.lang.Exception
("Have fun with this one");
}
// end methodB
public static void main (String [] args) {
methodA ();
}
// end main
} // end class Excaptions 0a
Finally
- Here we have added the finally clause - which is executed even
if the called method, methodB, throws the exception.
- Note that the yellow code inside the try part of the
try/catch/finallly block after the call to methodB is NOT
executed.
- BUT - the code in the finally clause IS executed.
- And, since the exception is handled in the try/catch/final
block, the code after the block (cyan) is also executed.
public class
Exceptions0c {
static
void methodA () {
try {
methodB();
System.out.println
("Everything was fine");
} catch
(java.lang.RuntimeException e) {
System.out.println (e.toString());
} finally {
System.out.println ("Finally clause: even if the exception was
thrown!");
} // end try/catch
System.out.println
("After the fox!");
} //
end methodA
static
void methodB () throws java.lang.Exception {
throw new java.lang.Exception
("Have fun with this one");
}
// end methodB
public static void main (String [] args)
{
methodA ();
}
// end main
} // end class Excaptions 0c
ND.