DEV Community

Hayes vincent
Hayes vincent

Posted on

Exception and Exception handling:

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;

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode
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);    
         }

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)