Hi. I am learning Java and now stuck in the exceptions chapter. I wrote a code to understand exception. But i am not getting why there is an error saying "Unreachable catch block".Please help me out here. Code is as shown.

public class GetException {
    static int i;
    public static void main(String[] args) {
        try{
            System.out.println(i);
        }catch(RandomExc RE){
            System.out.println("oops!! i is equal to zero!!");
        }
    }
    public void SomeExc() throws RandomExc{
        if(i==0)
            throw new RandomExc();
    }

}

public class RandomExc extends Exception {
   RandomExc(){
       super("not possible");
   }
}

Thanks in advance

System.out.println does not throw a RandomExc.

What you need to do is change SomeExc(); so it takes an int i, then calls the System.out.println method if i!=0 as well as throwing the Exception if i==0.

After that replace where the println in the main method with SomeExc(i), I suspect it will then work.

he doesn't really need to pass the int to the method, since it's a variable on class level. he does however may not forget to call the SomeExec method.

Oh! No...what a silly mistake...i forgot to call the SomeExc method...
:( Anyway thanks guys for your responses..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.