-1

I written my own two customized Exception one is checked and other is unchecked when i'm executing my code is shows only checked Exception Why i'm not able to get unchecked Exception output??

    class Test {  
   public static void main(String args[]) throws CheckedException {
       int i=0;
       int j=0;
       if(i==0){
           throw new CheckedException("Got Checked Exception");
       }
       if(j==0){
           throw new UncheckedException("Got Unchecked Exception");
       }
   }
}
class CheckedException extends Exception{
    CheckedException(String s){
        super(s);
    }
}
class UncheckedException extends RuntimeException{
    UncheckedException(String s){
        super(s);
    }
}

Output of above program is : Got Checked Exception ,But i'm expecting both output Got Checked Exception && Got Unchecked Exception. What mistake i'm doing here? and How can i overcome this?

Rohit Maurya
  • 730
  • 1
  • 9
  • 22
  • 1
    because the UncheckedException is not reachable. Change `int i=0`to `i=1` and you see the UncheckedException – Jens May 09 '17 at 07:41
  • you can not see both exceptions. If the first is thrown, the method will leave. – Jens May 09 '17 at 07:42
  • ok, now i wrote first UncheckedException and then CheckedException now output is showing UncheckedException ,but i want both Exception , is there any way to get both exception output?? – Rohit Maurya May 09 '17 at 07:50
  • No there is not. If you use a Debugger you see why. The code which throws the second exception is not executed – Jens May 09 '17 at 07:51
  • You are welcome – Jens May 09 '17 at 07:56

1 Answers1

2

In your program you have used throws in main() method and you have initialized i=0 and j=0.

the first if(i==0) satisfies and generated exception and program stopped. that is why second if condition part not executing.

if you want to check second condition initialize, i with something other than 0

like i=1 and execute

You can also use separate try catch block to test both cases

thank you

Rakesh Ray
  • 62
  • 1
  • 9