0

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 ");
    }
Samudra Ganguly
  • 637
  • 4
  • 24
  • 1
    The answer here is likely what you're looking for https://stackoverflow.com/questions/3495926/can-i-catch-multiple-java-exceptions-in-the-same-catch-clause – DLynch May 17 '21 at 19:41
  • 2
    Q: Should i use trycatch-block for each all issue? A: *NO*! You should be able to put multiple "catch" statements in the *SAME* "try" block. Q: Why couldn't I catch b.charAt() to "Null Pointer Exception" after arithmeticException? A: Because you probably didn't throw an NPE. If you did, your code should catch it. SUGGESTION: Add `catch Exception e) {...}` as the final clause in your try/catch block, repeat your "b.charAt(_)", and see what happens. – paulsm4 May 17 '21 at 19:42
  • Paul gives good advice. It is *seldom* a good idea to catch all exceptions like this. Newbies think it "prevents errors" but what it really does is hide the errors and prevent you from finding them. When learning, try to not catch any exceptions at all. Instead try to design the code so that it in fact never throws the exception. – markspace May 17 '21 at 19:44
  • Your code doesn't throw a NPE at `b.charAt(0)` because executing `int a = 6 / 0;` already throws an `ArithmeticException` and that means that control is transferred immediately to the `catch (ArithmeticException e)` block. The remaining statements in the `try` clause are never executed and therefore cannot throw exceptions. – Thomas Kläger May 17 '21 at 19:45
  • thank you guys for your answers. yo re great :) – Samet Yıldız May 17 '21 at 20:12
  • Does this answer your question? [Can I catch multiple Java exceptions in the same catch clause?](https://stackoverflow.com/questions/3495926/can-i-catch-multiple-java-exceptions-in-the-same-catch-clause) – Zaboj Campula May 18 '21 at 14:00

1 Answers1

2

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).

visconttig
  • 108
  • 8