简体   繁体   中英

How to handle Exception properly from a method?

Suppose, I have a method:

private void someMethod() {
    try {
        //Do something here
    }
    catch (NullPointerException ex) {
        System.out.println("error");
    }
}

Now, I want to use this method somewhere else:

private void newMethod() {
    someMethod();
    JOptionPane.showMessageDialog(null, "Exception didn't occur");  
}

Now, I want that if exception occurs in someMethod() , then newMethod() will not advance further, I mean, the JOptionPane message will not be shown in this case.

What will be the best way to do that? I have found a way by throwing another NullPointerException in catch block of someMethod() and then handling that from newMethod() . The code below demonstrates that:

private void someMethod() {
    try {
        //Do something here
    }
    catch (NullPointerException ex) {
        System.out.println("error");
        throw new NullPointerException("error");
    }
}

private void newMethod() {
    try {
        someMethod();
        JOptionPane.showMessageDialog(null, "Exception didn't occur");
    }
    catch (NullPointerException ex) {
        System.out.println("error");
    }           
}

But, by this method, I am facing some difficulties for other cases. I guess there are better ways to achieve that. Thanks anyway.

You don't need to handle the exception inside someMethod . Instead you can declare the exception in this method's throws clause (if it is a checked exception) and let newMethod handle it.

private void someMethod() throws SomeCheckedException {
   //Do something here
}

In case of NullPointerException, you don't need to do above, as it is an unchecked exception. Don't catch it inside someMethod , instead have try-catch inside newMethod .

It is good practice if your function intend to throw exception make it part of function declaration. So recommendation is to change someMethod() to private void someMethod() throws <exception Name> .

Depends on your requirement you can handle the exception in same method and throw another exception, or re throw same exception and handle it in another function.

In case you are re-throwing the same exception syntax is as follows:

private void someMethod() throws WhateverException  {
    try {
        //Do something here
    }
    catch (WhateverException e) {
        throw e;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM