Throwing multiple exceptions in Java

后端 未结 11 1423
无人及你
无人及你 2020-12-28 13:04

Is there any way to throw multiple exceptions in java?

相关标签:
11条回答
  • 2020-12-28 13:38

    I've seen a pattern, where a custom exception internally stores other exceptions (can't remember, why they did it), but it was like:

    public class ContainerException extends Exception {
    
      private List<Exception> innerExeptions = new Arrayist<Exception>();
    
      // some constructors
    
      public void add(Exception e) {
        innerExceptions.add(e);
      }
    
      public Collection<Exception> getExceptions() {
        return innerExceptions;
      }
    }
    

    and it was used like this:

    try {
      // something
    } catch (ContainerException ce) {
      ce.add(new RunTimeException("some Message");
      throw ce; // or do something else
    }
    

    Later in the code, the container exception was evaluated and dumped to a log file.

    0 讨论(0)
  • 2020-12-28 13:38

    Throwing more than a single exception doesn't make sense because you can't have more than a single error (the error can have multiple reasons but there can't be more than a single error at any time).

    If you need to keep track of the reasons, you can chain exceptions:

    } catch (Exception ex) {
        throw new RuntimeException("Exc while trying ...", ex);
    }
    

    These are available via getCause().

    0 讨论(0)
  • 2020-12-28 13:38

    I am unsure if you are asking whether multiple exceptions can be thrown at a time or we can have a code to handle multiple exceptions at a time. I will try to answer both of these. This is my first answer on StackOverflow so pardon any errors.

    1) If you want to throw multiple exceptions at a time,I think you can't do that. Consider an analogous situation. When you are solving a Math questions and reach a point where you are dividing by 0, there is only one error AT THIS POINT of time and that is dividing by zero. So I guess you can just throw one error for a given statement. However there can exist many statements in your try catch block each of which might throw a different error.

    2) IF you want to handle/catch multiple errors there are two ways to do it. i) Before Java 7:

    `try{
         ...
         //some method/action that can be a cause of multiple errors,say X and Y
         ...
     }catch(XException e){
          //Do something if exception X arises.
     }catch(YException e){
          //Do something if exception Y arises.
     }
    `
    

    ii) After Java 7,you have the multi catch feature.

    try{
         ...
         //some method/action that can be a cause of multiple errors,say X and Y
         ...
     }catch(XException|YException e){
       // Take action appropriate to both types of exception.
      ...
     }
    

    I believe this will solve your doubt. This being my first answer,all suggestions are welcome!

    0 讨论(0)
  • 2020-12-28 13:44

    there is a way for a method to throw mutiple exeptions, but not at one time. e.g. when compilation fails for some reason your method can only throw one exception. if you have to cover different opportunities you might declare you method to throw the parent class of all exceptions "Exception". so, if you declare a method to throw an Exception in general, an exception of any type can be thrown by this method.

    for example:

    public static void main(String[] args) throws Exception
    {
      getClipboard();    // throws an UnsupportedFlavorException
      initIOActivity();  // throw an IOException
    }
    

    i don't know what you actually needed to know but maybe this helps. although it has passed a lot of time since your post ^^

    greetings

    0 讨论(0)
  • 2020-12-28 13:50

    Piggybacking on aioobe's answer, what I did was throw each Exception into a list before adding them as suppressed exceptions to a new Exception, then threw the new one:

    Example:

    public JSONObject jsonExceptionExample(int value) throws JSONException {
        //Create Exception List
        List<JSONException> jsonExceptions = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        try {
    
            //Your code that could throw an Exception
            jsonObject.put("key", value);
    
        } catch (JSONException e){
            //Exception is caught and added to list instead of being thrown
            jsonExceptions.add(e);
        }    
        //Check to see if any Exceptions were caught
        if (jsonExceptions.size() > 0) {
            //Create a new Exception to be the 'parent' Exception
            JSONException jsonException = new JSONException("JSONException(s) thrown");
            //Iterate through your list of errors
            for (JSONException e : jsonExceptions) {
                //Add each one to the parent Exception as 'Suppressed'
                jsonException.addSuppressed(e);
            }
            //Throw your new nested error
            throw jsonException;
        }
        //If no Exceptions were found, resume your code
        return jsonObject;
    }
    

    To avoid an import if you don't already have a List elsewhere, you could also just throw a new Exception instead of initializing a list, add your errors to it with addSuppressed()`` in the catchblock, and later callException.getSuppressed().length > 0``` to determine if any were added to it, but I just like the list for the readability and the general rationale that I don't want to create an Exception without there actually being an error.

    0 讨论(0)
  • 2020-12-28 13:51

    I suppose you could create an exception containing a list of caught exceptions and throw that exception, e.g.:

    class AggregateException extends Exception {
        List<Exception> basket;
    }
    
    0 讨论(0)
提交回复
热议问题