SHE SHE - 1 month ago 13
Java Question

Try catch throw confusion

I have read a lot throws issues in stackoverflow but it did not help me. Based on this article: link


If any method throws checked Exception, than caller can either handle this exception by catching it or can re throw it by declaring another throws clause in method declaration.


So method1 will throw a
CheckedException


public static void method1() throws CheckedException {
}


In the caller function we can either catch that exception and do something about it

public static void method2() {
try{
method1();
}
catch(CheckedException e){
System.out.print("too bad");
}
}


or we can re-throw it and maybe handled by another function who calls method2 in the future?

public static void method2() throws CheckedException{
method1();
}


Am I undertanding in the correct way?

Answer

If a method internally does something which can cause a checked exception, then you have two choices for dealing with it. You can either have that method throw an exception itself, or you can surround the code which might cause the checked exception with a try catch block.

Option 1:

public static void method1() throws SomeCheckedException {
    String  intNumber = "5A";
    // now just call the method in question without checking
    exception();
}

Option 2:

public static void method1() {
    String  intNumber = "5A";
    // handle the checked exception here directly in the method
    try {
        exception();
    }
    catch (SomeCheckedException e) {
        // handle exception right here
    }
}