Search code examples
javaexceptionpropagationthrowschecked-exceptions

Is there any other role of throws instead of propagating a checked Exception?


After studying more and more about throws statement in Exception Handling I am getting confused.I found-

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.

class Boxing1{  
public static void main(String args[]) throws IOException{
    new B().meth2();
    System.out.println("33333333");
}
}
class A{

    void meth1() throws IOException{
        throw new IOException();
        //throw new NullPointerException();
        //System.out.println("111111111111");
    }
}
class B{
    void meth2() throws IOException{
        new A().meth1();
        System.out.println("2222222");
    }
}

Instead of using throws there is still an exception- My console is showing following error-

Exception in thread "main" java.io.IOException
    at A.meth1(Boxing1.java:17)
    at B.meth2(Boxing1.java:24)
    at Boxing1.main(Boxing1.java:10)

Untill I am not putting calling of meth1 in try-catch block there is a exception in spite of using throws. What is the role of throws here?

try{new A().meth1();}catch(Exception e){System.out.println(e);}

I needed your confirmation on it.I am confused.My one line Query is-

Is there any other role of throws instead of propagating a CheckedException?


Solution

  • As you said, there are 2 kinds of exceptions.

    • "Checked exceptions" need the attention of the developer. When you use a method that throws a checked exception (i.e. IOException), you need to handle it (i.e. catch it) or propagate it to the caller (i.e. throw it) assuming that the caller will catch it.

    • "Unchecked exceptions" don't need special attention. These are exceptions like NullPointerException, bugs. You don't want to write code to cover potential bugs. It's impossible to cover everything. Nevertheless, if you want to catch an unchecked exception, you can.

    • Note: There are some other throwable objects. You can throw all objects that extend the Throwable class. But you shouldn't use this functionality in your code. This is really for system Errors and Assertions.

    If you throw a checked exception then you need to warn developers by specifying throws SomeException in your method signature. For an unchecked exception you don't.

    The compiler checks this. It recognizes unchecked exceptions easily, because unchecked exceptions extend the RuntimeException class.

    Finally, in your case you propagated the exception all the way to the top, to your main() method. And even there you continued propagating it. The JVM will just print it in that case.