Monday, July 2, 2012

Unusual things in Exceptions


I called this post "Unusual things in Exceptions" because you're going to see something that isn't usually used in a real word as well as staffs that you have to memorize for the OCJP certification.

Let's start with the class hierarchy:


package br.com.ocjp.exception;
import java.io.IOException;
public class ExceptionOrder {
public static void doSomething() {
try {
String s = "Exception example";
} catch (IOException e) { // does not compile
}
}
}
view raw gistfile1.java hosted with ❤ by GitHub

The code above does not compile you cannot handle an exception if the block try does not "throw" one.

!Import
The block finally always is called, even if there is a return statement in the try/catch block, the finally block will be executed before the return stamement.

package br.com.ocjp.exception;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExceptionOrder {
public static void doSomething() {
try {
new FileOutputStream( new File("C:\\file.txt"));
} catch (IOException e) {
} catch (FileNotFoundException e) { // does not compile
}
}
}
view raw gistfile1.java hosted with ❤ by GitHub

In this case the block try "throws" an exception throught the creation of FileOutputStream, but we still getting a compiler error, because the catch that handles FileNotFoundException will never be reached.
package br.com.ocjp.exception;
import java.io.IOException;
public class ExceptionCatchDeclare {
public void doSomething()/* throws IOException*/ {
throw new IOException(); // does not compile you have to declare(throws)
}
public void doAnything() {
doSomething(); // here you have to handle(try/catch) or declare(throws)
}
}
view raw gistfile1.java hosted with ❤ by GitHub

That's the rule for checked exceptions if you throw an exception you must declare(throws) from the calling method or catch(try/catch).


Different from checked exception, every exception under RuntimeException/Error are not obligated to catch or declare, but if you did you would be able to catch it by using try/catch block.
package br.com.ocjp.exception;
public class ExceptionRunTime {
public void doIt() throws ArithmeticException {
throw new ArithmeticException();
}
public void doThat() {
doIt();
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Common Exception

Let's take a look at the common exception, watch out where they come from





No comments: