Back OCAJP
There are two ways a method can throw an exception: implicitly and explicitly.
1. For example, wrong code that compiles can throw exception:
int a = 10/0;
This code will throw java.lang.ArithmeticException: / by zero.
2. explicitly throw one. For example:
throw new Exception("you must handle");
throw new RuntimeException("you are Ok to not handle, and you are Ok to handle");
throw new Error("you are Ok to not handle, and you are not OK to handle.");
When calling methods that throw exceptions, you can either declare exception or handle exception.
If you don't, the code won't compile
OCAJP>cat Test.java
import java.io.IOException;
class Test {
public static void main(String[] args) {
readAFile();
}
public static void readAFile() throws IOException{}
}
OCAJP>javac Test.java
Test.java:4: error: unreported exception IOException; must be caught or declared to be thrown
readAFile();
^
1 error
Even though readAFile method didn't actually throw an exception, it just declared that it could. This is enough for the compiler to require the caller to handle or declared the exception. The catch block in caller may not catch anything, but it is ok for the compiler.
OCAJP>cat Test.java
import java.io.IOException;
class Test {
public static void main(String[] args) {
try{
readAFile();
} catch (IOException e) {
System.out.println("not reachable");
}
}
public static void readAFile() throws IOException{}
}
OCAJP>javac Test.java
OCAJP>java Test
OCAJP>
Because the method may also actually throw something sometimes.
OCAJP>cat Test.java
import java.io.IOException;
class Test {
public static void main(String[] args) {
try{
readAFile();
} catch (IOException e) {
System.out.println("not reachable."+e.getLocalizedMessage());
}
}
public static void readAFile() throws IOException{
throw new IOException("really not reachable?");
}
}
OCAJP>javac Test.java
OCAJP>java Test
not reachable.really not reachable?
OCAJP>
alternatively, you can have main method to declare the exception.
OCAJP>cat Test.java
import java.io.IOException;
class Test {
public static void main(String[] args) throws IOException{
readAFile();
}
public static void readAFile() throws IOException{}
}
OCAJP>javac Test.java
OCAJP>java Test
OCAJP>
Back OCAJP