Unchecked Exception = Error + RuntimeException
Checked Exception = RuntimeException
Compiler requires you to provide handlers for all checked exceptions.
RuntimeException is programmer’s fault, which means this can be avoided by proper testing in the program
NOTE: override methods in subclass CANNOT throw more general exceptions than superclass methods. But it is OK to throw more specific exceptions. If superclass methods do not throw checked exceptions, subclass methods CANNOT throw any.
If a method declares to throw an exception, it may throw an exception of that class or of any of its subclasses.
Return value in finally block will mask the return value in try block. This may not what you want, be cautious.
To declare a method can throw an exception
public Image loadImage(String s) throws FileNotFoundException, EOFException
To throw an exception
if(nthrow new EOFException();
}
Below style is strongly recommended
* Code is more readable, inner try/finally block has single responsibility, outer try/catch block also has single responsibility
* If having exceptions in finally block, e.g., fail to close resource, they can be handled properly in the outer catch block
try {
try {
// code that may throw exceptions
}
finally {
// close resource here
}
}
catch (IOException e) {
// handle exceptions
}
Create your own exception
class FileFormatException extends IOException {
public FileFormatException() {
}
public FileFormatException(String message) {
super(message);
}
}
As of Java SE7, you can catch multiple exception types in the same catch clause
* Catching exception types are not subclasses of one another
* Make your code look simpler and more efficient
try {
// code might throw exceptions
}
catch (FileNotFoundException | UnkonwnHostException e) {
// handler
}
catch(IOException e) {
// handler
}
Rethrowing and Chaining Exceptions
try {
// code that might cause SQLException
}
catch (SQLException e) {
Throwable se = new ServletException("database error");
se.initCause(e);
throw se;
}
Later you can
Throwable e = se.getCause();
As of Java SE 7, you can use try-with-resource statement
* If resource implement AutoCloseable interface (or Closable interface which is a sub interface of Autoacloseable). This interface has a single close method
* If both try block and close throw exceptions, the original exception is rethrown, and others thrown by close are caught and added to the original exception with addSuppresed() method, you can later get them by calling getSuppresed() method
try (Scanner in = new Scanner(new FileInputStream("/usr/share/dict/words")),
PrintWriter out = new PrintWriter("out.txt")) {
// Your code that might throw exceptions
}