Search code examples
javaexceptionnullpointerexceptiontry-catcharithmetic-expressions

How to catch two or more Exceptions in JAVA?


how can i catch 2 or more exception in same time ? Should i use trycatch-block for each all issue ?

For example, i couldn t catch b.charAt() to "Null Pointer Exception" after arithmeticException.

try{
    int a = 6 / 0 ;
    String b = null;
    System.out.println(b.charAt(0));
        
        
    }
    catch(NullPointerException e){
        System.out.println("Null Pointer Exception");
    }
    catch(ArithmeticException e){
        System.out.println("Aritmetic Exception ");
    }

Solution

  • In Java SE 7 and later, you actually can catch multiple exceptions in the same catch block.

    To do it, you write it this way:

             try{
        // Your code here
            } catch (ExampleException1 | ExampleException2 | ... | ExampleExceptionN e){
        // Your handling code here
        }
    

    Besides that, you can use an extremely general catching exception like:

    try{
    // code here
    } catch (Exception e){
    // exception handling code here
    }
    

    But, that is a discouraged practice. ;)

    Resources: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html (Oracle Documentation).