Skip to content

Instantly share code, notes, and snippets.

@Kaushal28
Created July 22, 2019 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kaushal28/1380636f978f5d53b54d38c8e2b78790 to your computer and use it in GitHub Desktop.
Save Kaushal28/1380636f978f5d53b54d38c8e2b78790 to your computer and use it in GitHub Desktop.
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