What is an Exception?
An exception is an error that occurs during program execution (runtime) and disrupts the normal flow of the program.
int a = 10;
int b = 0;
int c = a / b;
What is Exception Handling?
Exception handling is a mechanism to handle these runtime errors so that the program does not crash and continues execution.
public class Main {
public static void main(String[] args) {
try {
int a = 10 / 0; // exception
} catch (ArithmeticException e) {
System.out.println("Error handled");
}
}
}
Output: Error handled
package Learning;
public class ExceptionDemo {
public static void main(String[]args) {
ExceptionDemo ed=new ExceptionDemo ();
int i=5;
int j=0;
ed.multiplay(i, j);
ed.divide(i, j);
ed.add(i, j);
}
public void multiplay(int i,int j) {
System.out.println("Mulitplay:" + i*j);
}
public void divide(int i,int j) {
try {
System.out.println("Division:" + i/j);
}catch(ArithmeticException ed) {
System.out.println("will check");
}}
public void add(int i,int j) {
System.out.println("Add:"+ i+j);
}
}
Top comments (0)