mitesh
mitesh

Reputation: 347

Throwing Exceptions from Exception class in java

Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}

Working Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}

Why doesn't it work with Exception class and worked with its subclass??

Note :- The error i get in the error code is Unhandled exception type Exception

Upvotes: 1

Views: 2852

Answers (3)

Zoltán Raffai
Zoltán Raffai

Reputation: 141

It's because they are several Exception classes which are inherited from the class Exception. Each can be throwed, catched but they divide into two groups:

Checked and unchecked exceptions:

  1. An unchecked exception doesn't need to be handled and the NullPointerException which you tried is from that group, so you don't need to care about it technically.
  2. A checked exception need to be handled every time or it won't compile, these exceptions are like IOException.

Since the base Exception Object can be checked and unchecked as well the compiler cares about that it should be handled everytime.

If you give it a try and change the NullPointerException to IOException it won't compile either cause it is a Checked Exception. So it was just random, that you exactly find one type of Exception which your code can be work without compile error.

For more info visit my blog post about it: http://www.zoltanraffai.com/blog/?p=93

Upvotes: 0

J-Alex
J-Alex

Reputation: 7107

  1. Runtime exceptions extend RuntimeException. They don’t have to be handled or declared. They can be thrown by the programmer or by the JVM.

  2. Checked exceptions have Exception in their hierarchy but not RuntimeException. They must be handled or declared. They can be thrown by the programmer or by the JVM.

  3. Errors extend the Error class. They are thrown by the JVM and should not be handled or declared.

When method throws checked exception (1) you should handle or rethow it.

When method throws uncheked exception (2) you can handle or rethrow it, but it's not obligatory.

But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main)

It means that your method is throwing checked exception which should be handled or rethrowed.

Handling:

public class Main {

    public static void main(String[] args) {
        try {
            throw new Exception();
        } catch (Exception e) {
            try {
                throw new Exception();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}

Rethrowing:

public class Main {

    public static void main(String[] args) throws Exception {
        try {
            throw new Exception();
        } catch (Exception e) {
            throw new Exception();
        }
    }
}

In your case:

// You declaring that the caller should handle exception
static void renderWorld() throws Exception {
       try {
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           } else {
                System.out.println("The World is Empty!");
           }
       } catch(Exception e) {
           System.out.println("Please handle the error");
           // You cannot just throw uncheked exception here
           // You should handle it yourself or a caller should do it
           throw e;
       }
}

Upvotes: 1

Naman
Naman

Reputation: 31868

Changing

static void renderWorld() { ... }

to

static void renderWorld() throws Exception { ... }

should fix this. This is for the reason that runtime exception are unchecked exceptions.

Would recommend you to read about the Checked and Unchecked exception in details here - Java: checked vs unchecked exception explanation.

Upvotes: 0

Related Questions