Difference between revisions of "Exceptions"
From Suhrid.net Wiki
Jump to navigationJump to searchLine 22: | Line 22: | ||
* If exceptions are in different class hierarchy, then the order does not matter. | * If exceptions are in different class hierarchy, then the order does not matter. | ||
* Each method must follow the handle or declare law for checked exceptions. | * Each method must follow the handle or declare law for checked exceptions. | ||
+ | |||
+ | * The compiler will check if the code within the try block can throw the exceptions in the catch block, if not it will flag an error. See below: | ||
+ | |||
+ | <syntaxhighlight lang="java5"> | ||
+ | |||
+ | public static void main(String[] args) { | ||
+ | try { | ||
+ | f(); | ||
+ | } catch(FileNotFoundException f) { | ||
+ | |||
+ | } catch(InterruptedException e) { //This will be a compiler error, since f() can never throw InterruptedException | ||
+ | |||
+ | } | ||
+ | } | ||
+ | |||
+ | private static void f() throws FileNotFoundException { | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | |||
+ | |||
[[Category:OCPJP]] | [[Category:OCPJP]] |
Revision as of 22:45, 20 July 2011
Introduction
- Exceptions are a mechanism to detect and handle errors without writing special code to test return values.
- Error handling code for common errors can be handled in a single place.
Structure
- A try clause has to have either a catch clause or a finally clause or both.
- catch must follow try.
- finally must follow the last catch clause.
Exception Hierarchy
- All exception classes are subtypes of java.lang.Exception.
- RunTimeException is a subtype of Exception which represents unchecked exceptions. All unchecked exception will inherit from this class.
- Classes which derive from java.lang.Error indicate serious problems that an application should not try to catch. e.g OutOfMemory error.
- Both Error and Exception classes are derived from the java.lang.Throwable class.
Exception Handling
- The order of catch clauses is important.
- If the exceptions are in the same class hierarchy, The most-specific exception type should be first, followed by the more general exceptions. Otherwise, the code will not compile.
- If exceptions are in different class hierarchy, then the order does not matter.
- Each method must follow the handle or declare law for checked exceptions.
- The compiler will check if the code within the try block can throw the exceptions in the catch block, if not it will flag an error. See below:
public static void main(String[] args) {
try {
f();
} catch(FileNotFoundException f) {
} catch(InterruptedException e) { //This will be a compiler error, since f() can never throw InterruptedException
}
}
private static void f() throws FileNotFoundException {
}