How to call a method that throws an exception in catch block?

11,790

Solution 1

This is because the exception that was thrown on handleException is already caught by the catch block of the foo method. Thus the foo method no longer throws an Exception making the catch block return nothing. So if the bar method throws an exception it will go to the catch block but since the catch block is not returning anyting, Java executes the lines after the catch block but when it reaches the end it throws an error that "the method must return a result of type int" since you do not have a return statement.

You should change this part.

public class MyException {

    static int foo(int num) throws Exception {
        try {
            return bar(num);
        } catch (Exception e) {
            throw handleException(e); // this will throw the exception from the handleException
        //    throw new Exception("Exception in foo", e);
        }
    }

    static int bar(int num) throws IllegalArgumentException {
        if (num < 0) {
            throw new IllegalArgumentException("Num less than 0");
        }
        return num;
    }

    // This method now returns an exception, instead of throwing an exception
    static Exception handleException(Exception e) {
        System.err.println("Handling Exception: " + e);
        return new Exception(e);
    }

    public static void main(String[] args) throws Exception {
        int value = foo(-1);
    }
}

Solution 2

In my original class, I have lot of methods that have this format... I am trying to come up with a cleaner way to write the catch blocks.

I think the issue is more to do with understanding how the exceptions are handled in applications; its a design issue, in general.

Consider the method: int foo(int num) throws Exception

The method foo returns a value, catches an exception/handles and also throws an exception. Consider these aspects.

If the method runs normally, without errors, it returns a value. Otherwise, if there is a problem with its logic, throws an exception within the method, catches it and handles it within the catch-block of the method. The method also throws an exception.

There are two options here to consider:

  1. Re-throw an exception, like a custom business/application exception (just log it and re-throw the same or a custom exception), which needs to be handled elsewhere - that is in a calling method up the stack.
  2. Handle the exception: This means that the method takes care of the exception. Some business/application logic happens within the exception handling. And, the method returns a value.

The purpose of a method throwing an exception is that it is handled elsewhere, like in a calling method. The handling can be like recovering from the exception problem or displaying a message or aborting a transaction or whatever the business logic defines.

Is the exception thrown because of a business logic issue? If so it is likely that you show a message to the user or do some other logic about it and/take further steps to recover from it - as the business rules permit it.

In case the exception is thrown as a result of a situation which is not recoverable by the application's logic, do appropriate actions.

Ultimately, you have to have a clear requirement about why an exception is thrown, what you do with the exceptions thrown and how you handle them in the application. The application/logic/rules requirement influences in designing the exception handling in the code.

Notes (edit-add):

  • There are quite a few articles which explain about exception handling in business application out there on the net. One can try a search string like "Java exceptions best practices". Here is one such article which has some useful info: Effective Java Exceptions.
  • There is also the try-catch-finally construct to consider (along with various new exception features introduced with Java 7).

Solution 3

foo method's return type is int and return type of handleException is void, that is why compiler gives error.

(1) Here you could solve this as follows:

Throw exception as is again.

try{
      return bar(num);
}
catch(Exception e){
      handleException(e);
      throw e;
}

(2) Moreover if you want to throw new created exception then change return type of handleException to Exception. Use

throw handleException(e);
Share:
11,790
SyncMaster
Author by

SyncMaster

Updated on July 11, 2022

Comments

  • SyncMaster
    SyncMaster almost 2 years

    I am trying to have an HandleException method that can handles various exceptions.

    The problem is, my function returns a value. But if I use HandleException in my catch block, Java complains that the function does not return a value even though my HandleException always throw an exception.

    What is a good way to fix this? Thanks!

    Here is a sample code.

    public class MyException {
    
        static int foo(int num) throws Exception {
            try {
                return bar(num);
            } catch (Exception e) {
                handleException(); 
            //    throw new Exception("Exception in foo", e);
            }
        }
    
        static int bar(int num) throws IllegalArgumentException {
            if (num < 0) {
                throw new IllegalArgumentException("Num less than 0");
            }
            return num;
        }
    
        static void handleException(Exception e) throws Exception {
            System.err.println("Handling Exception: " + e);
            throw new Exception(e);
        }
    
        public static void main(String[] args) throws Exception {
            int value = foo(-1);
        }
    }
    

    In my original class, I have lot of methods that have this format.

    try {
        ...
    } catch (Exception1) {
        Log exception
        throw appropriate exception
    } catch (Exception2) {
        Log exception
        throw appropriate exception
    }
    

    I am trying to comeup with a cleaner way to write the catch blocks.

    • Marco
      Marco about 5 years
      i don't understand you question... what are try to do, throw and exception and catch it in another method?
    • prasad_
      prasad_ about 5 years
      Your code MyException.java doesn't compile. Here is some useful notes on exceptions and their handling at Oracle's Java tutorials Exceptions.
    • xerx593
      xerx593 about 5 years
      try static int handleException(Exception e)... ..and then return it in catch block.
    • SyncMaster
      SyncMaster about 5 years
      As I mentioned this is just a sample code that I wrote to explain the bigger problem I am trying to solve.