Exception Handling
Exception handling is a way for a program to deal with errors that happen while it runs, such as a missing file, a failed network call or dividing by zero, without crashing. When an error occurs, the code "throws" an exception, and the nearest matching handler "catches" it and decides what to do.
Most languages use try, catch (or except) and finally blocks: the try block contains code that might fail, the catch block handles the error, and the finally block always runs, usually to close files or connections. In Java, checked exceptions must be caught or declared, while unchecked exceptions, such as NullPointerException, need not be.
package in.ihelpyou;
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This always runs");
}
}
}