DEV Community

Saravanan B
Saravanan B

Posted on

Core Java - Exception Handling.

Runtime error are exception and we need to handle it.

public class Test {
    public static void main(String[] args) {
        int a=12/8;
        System.out.println("Result : "+a);
        System.out.println("Before Exception");
        int b = a/0; //Exception code
        System.out.println("Result : "+b);
        System.out.println("After exception");
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Arithmetic Exception - it happens when we try to do calculations like divide by zero.
Number format Exception - it happens when we try to parse a string into integer.
ArrayIndexOutOfBound - trying to access the element with the index out of bounds means array size is 4 and trying to access element at 5 is out of bound.
NullPointerException - It happens when we call the method of object without creating instance of it.

public class ArrayIndexOutOfBound {
    public static void main(String[] args) {
        int a[] = {1,2,3};
        System.out.println("Trying to get element at 4 : "+ a[4]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output - java.lang.ArrayIndexOutOfBoundsException

public class ArrayIndexOutOfBound {
    public static void main(String[] args) {
        int a[] = {1,2,3};
        System.out.println("Trying to get element at 4 : "+ a[4]);
    }
    void method1() {
        System.out.println("null");
    }
}
Enter fullscreen mode Exit fullscreen mode
public class NullPointer {
    static ArrayIndexOutOfBound a;

    public static void main(String[] args) {
        NullPointer.a.method1();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output - java.lang.NullPointerException

We can handle a exception using try catch throw finally and throws.

try{
code that cause exception
}catch(Exception e){
Exception
}

Handling Arithmetic Exception.

public class Arithmatic {
    public static void main(String[] args) {
        try {int b = 12 / 0; // Exception code
        } catch (Exception e) { System.out.println(e+ ": can't divide by zero");}
        System.out.println("After exception");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -- java.lang.ArithmeticException: / by zero: can't divide by zero
After exception

Handling ArrayIndexOutbound

public class ArrayIndexOutOfBound {
    public static void main(String[] args) {
        int a[] = { 1, 2, 3 };

        try {
            System.out.println("Trying to get element at 4 : " + a[4]);
        } catch (Exception e) {
            System.out.println(e);
        }

        System.out.println("After exception Code");
    }
Enter fullscreen mode Exit fullscreen mode

Output -- java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
After exception Code

Handling NullPointerException.

public class NullPointer {
    static ArrayIndexOutOfBound a;
    public static void main(String[] args) {
        try {
            NullPointer.a.method1();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -- java.lang.NullPointerException: Cannot invoke "com.exception.ArrayIndexOutOfBound.method1()" because "com.exception.NullPointer.a" is null

Once we handled an exception using parent class like Exception and then we try to handle specific exceptions after parent exception it will throw an error.

Checked Exception needs to be handled unlike unchecked Exception otherwise compiler won't compile the program.

Finally -- even if there is exception or not this block will gets executed always.

throws -- We don't want to write catch for a method and we want the method to handle the exception we use throws keyword.

public class tryingThrows {
    public static void main(String[] args) throws FileNotFoundException{
        tryingThrows ty = new tryingThrows();
        ty.fis();
        System.out.println("After Exception");
    }
    void fis() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("");
    }
}
Enter fullscreen mode Exit fullscreen mode

It will throw a exception and not execute the code after the exception throws keyword is used to just to declare that the method not gonna handle exception but whichever implements needs to handle.

Throw -- Explicitly throw exception or throw our own exception.

public class Throw {
    public static void main(String[] args) {
        throw new RuntimeException("Trying throw");
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

In checked Exception we need to handle the with try catch for throw.

custom Exception --

Unchecked Custom Exception -

public class UncheckedCustomException extends RuntimeException {
    UncheckedCustomException(String message){
        super(message);
    }
}
Enter fullscreen mode Exit fullscreen mode
public class Test {
public static void main(String[] args) {
    throw new UncheckedCustomException("Business Exception");
}
}
Enter fullscreen mode Exit fullscreen mode

Output -
Image description

Checked Exception-

public class CheckedCustomException extends Exception{
    CheckedCustomException(String message){
        super(message);
    }
}
Enter fullscreen mode Exit fullscreen mode
public class TestChecked {
    public static void main(String[] args) throws CheckedCustomException {
        throw new CheckedCustomException("Checked Custom Exception");
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description


Assertions - Testing and debugging.

Assert expression;
Used for testing in junit and spring..

public class Assert {
public static void main(String[] args) {
    int a=10;
    int b=20;
    assert(a>b):"Condtion not satisfied";
}
}
Enter fullscreen mode Exit fullscreen mode

Image description

If the condition passed return nothing else throws exception.

Top comments (0)