Java Reference
In-Depth Information
The compiler is very particular about checked exceptions being handled by programmers. If the code in a
try
block cannot throw a checked exception and its associated
catch
blocks catch checked exceptions, the compiler
will generate an error. Consider the following code, which uses a
try-catch
block. The
catch
block specifies an
IOException
, which is a checked exception. However, the corresponding
try
block does not throw an
IOException
.
// CatchNonExistentException.java
package com.jdojo.exception;
import java.io.IOException;
// Will not compile
public class CatchNonExistentException {
public static void main(String[] args) {
int x = 10, y = 0, z = 0;
try {
z = x / y;
}
catch(IOException e) {
// Handle exception
}
}
}
When you compile the code for the
CatchNonExistentException
class, you would get the following compiler error:
Error(12): exception java.io.IOException is never thrown in body of corresponding try statement
The error message is self-explanatory. It states that
IOException
is never thrown in the
try
block. Therefore, the
catch
block must not catch it.
One way to fix the above compiler error is to remove the
try-catch
block altogether. The following is another
interesting way (but not a good way) to mention a generic
catch
block:
// CatchNonExistentException2.java
package com.jdojo.exception;
// Will compile fine
public class CatchNonExistentException2 {
public static void main(String[] args) {
int x = 10, y = 0, z = 0;
try {
z = x / y;
}
catch(Exception e) {
// Handle the exception
}
}
}