Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.FileNotFoundException;
/**
* Most common checked and unchecked exceptions
* https://stackoverflow.com/questions/1263128/most-common-checked-and-unchecked-java-exceptions
*/
class ExceptionExample {
//This is throwing (possibility of throwing) checked exception
void sampleMethod() throws FileNotFoundException {
System.out.println("I'm throwing FileNotFoundException");
}
//This is throwing unchecked exception
void sampleMethod1() throws NullPointerException {
System.out.println("I'm throwing NullPointerException");
}
}
public class TypesOfExceptions {
public static void main (String[] args) {
ExceptionExample ex = new ExceptionExample();
//Calling method which can throw Checked exception needs to be wrapped in a try/catch block. So this will give compile time error.
// ex.sampleMethod();
//Calling method which can throw unchecked exception can be called directly.
ex.sampleMethod1();
try {
ex.sampleMethod();
} catch (FileNotFoundException e) {
//Don't swallow exception with empty catch. Log it!
System.out.println(e.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment