Professional Documents
Culture Documents
Exception Hierarchy
Error represent unusual situations that are not caused by program errors, and indicate things that would not normally happen during program execution, such as the JVM running out of memory. The term "exception" means "exceptional condition" and is an occurrence that alters the normal program flow.
Handling Exception
- Using try and catch block - Using throws
The try is used to define a block of code in which exceptions may occur. This block of code is called guarded region (which really means "risky code goes here"). One or more catch clauses match a specific exception (or group of exceptionsmore on that later) to a block of code that handles it.
try { // Put code here that might cause some kind of exception. // We may have many code lines here or just one. } catch(MyFirstException) { // Put code here that handles this exception.
finally
A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not.
try { // Put code here that might cause some kind of exception. // We may have many code lines here or just one.
} catch(MyFirstException) {
// Put code here that handles this exception. } finally{ // Put code here to release any resource we // allocated in the try clause. }
Exam hint
It is illegal to use a try clause without either a catch clause or a finally clause. A try clause by itself will result in a compiler error. Any catch clauses must immediately follow the try block. Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch). It is legal to omit either the catch clause or the finally clause, but not both.
// do stuff
} System.out.print("below the try"); //Illegal! catch(Exception ex) { }
void myFunction() throws MyException1, MyException2 { // code for the method here }
e.g. void doStuff() { try{ doMore(); }catch(IOException e){ } } void doMore() { throw new IOException(); }
Resist the temptation to write a single catchall exception handler such as the following: try { // some code } catch (Exception e) { e.printStackTrace(); } Instead use the following block of code: try{ }catch(FileNotFoundException fe){} catch(IOException i){}
Contd
try { // do risky IO things } catch (IOException e) { // handle general IOExceptions } catch (FileNotFoundException ex) { // handle just FileNotFoundException } You'll get a compiler error something like this: TestEx.java:15: exception java.io.FileNotFoundException has already been caught } catch (FileNotFoundException ex) {}
Resist the temptation to write a single catchall exception handler such as the following: try { // some code } catch (Exception e) { e.printStackTrace(); } Instead use the following block of code: try{ }catch(FileNotFoundException fe){} catch(IOException i){}
What is an assertion?
An assertion is a statement in Java that enables you to test your assumptions about your program. Each assertion contains a boolean expression that you believe will be true when the assertion executes. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors
private void methodA(int num) { if (num >= 0) { useNum(num + x); } else { // num must be < 0 // This code should never be reached!
debugged, but disabled when the application is deployed. The assertions are
still in the code, although ignored by the JVM, so if you do have a deployed application that starts misbehaving, you can always choose to enable assertions in the field for additional testing.
The assertion statement has two forms The first is: assert Expression1 ; Where Expression1 is a boolean expression When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no details
where:
Expression1 is a boolean expression Expression2 is an expression that has a value It cannot invoke of a method that is declared void
Use the second version of the assert statement to provide a detailed message for the AssertionError The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string error message The purpose of the message is to communicate the reason for the assertion failure
Assertion failures are labeled in stack trace with the file and line number from which they were thrown Second form of the assertion statement should be used in preference to the first when the program has some additional information that might help diagnose the failure
Compiler Directives
For the javac compiler to accept code with assertions, use this command-line option: -source 1.4 For example: javac -source 1.4 MyClass.java
Assertions may be enabled and disabled Assertions are, by default, disabled at run-time
or
java -enableassertions com.geeksanonymous.TestClass
Arguments
no arguments Enables or disables assertions in all classes packageName... Enables or disables assertions in the named package and any subpackages className Enables or disables assertions in the named class
Don't Use Assertions to Validate Arguments to a Public Method Do Use Assertions to Validate Arguments to a Private Method Don't Use Assert Expressions that Can Cause Side Effects!
The following would be a very bad idea: public void doStuff() { assert (modifyThings()); // continues on } public boolean modifyThings() {
y = x++;
return true; }
2009 Deloitte Touche Tohmatsu
Q&A
2009 Deloitte Touche Tohmatsu