UkFLSUI
UkFLSUI

Reputation: 5672

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.

Upvotes: 1

Views: 79

Answers (2)

Steephen
Steephen

Reputation: 15824

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;
    }

}

Upvotes: 1

curlyBraces
curlyBraces

Reputation: 1105

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.

Upvotes: 3

Related Questions