What is an exception in Java? What are checked and unchecked exceptions?
An exception is an event which stops the normal flow of the program. Java gives an object of the exception, and you can catch it with try and catch.
| Type | Must handle? | Example |
|---|---|---|
| Checked | Yes, the compiler forces it | IOException, SQLException |
| Unchecked (RuntimeException) | No | NullPointerException, ArithmeticException |
| Error | No, do not catch | OutOfMemoryError |
public class Main {
public static void main(String[] args) {
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("finally runs always");
}
}
}
Output
Caught: / by zero
finally runs always
See Java Exceptions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |