0

what is the difference between writing a catch block which catches Exception object and catch block which catches Error object? when I am writing Only Error catch block it executes and catches the exception the same result as an exception but when writing with two catch block it executes exception catch block instead of catch block of error. someone can explain in detail.

public class Main
{
    public static void main(String[] args) {
        int a=1,b=0;
        try{
            System.out.println(a/b);

        }catch(Error e){
            System.out.println("error"+e);
        }
         catch(Exceptione){
            System.out.println("exception"+e);
        }
    }
}
MangduYogii
  • 935
  • 10
  • 24
  • `catch (Error)` catches all instances of Error and its subclasses (recursively). Those do **not** include Exception. `catch (Exception)` catches all instances of Exception and its subclasses (recursively). Those do **not** include Error. – JB Nizet Oct 23 '19 at 06:49
  • when I try with only try{ System.out.println(a/b); }catch(Error e){ System.out.println("error"+e); } it works – MangduYogii Oct 23 '19 at 06:52
  • Define "it works". What is a? What is b? What do you expect to happen? What actually happens? – JB Nizet Oct 23 '19 at 06:54
  • it gives me the same output as catching the exception – MangduYogii Oct 23 '19 at 06:54
  • 2
    No, it doesn't. Compare the two outputs you get: one is generated by the JVM itself and contains a stack trace. The other is generated by your `catch(Exception)` block and just contains the message you print. – JB Nizet Oct 23 '19 at 06:58
  • yes got it it prints only Exception msg generated by my catch(Exception) or if generated my JVM it does not print error msg my catch(Error) – MangduYogii Oct 23 '19 at 07:02

0 Answers0