Throwing multiple exceptions in Java

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

Is there any way to throw multiple exceptions in java?

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

    To throw multiple exceptions in Java you'll first have to suppress each exception into one customized exception and then throw the same customized exception. Please check the below code snippet to achieve the same.

      public class AggregateException extends Exception {
    
    
            public void addException(Exception ex){
    
            addSuppressed(ex);
            exception = true;
        }
    }
    
    
    public class AnyClass{
    
        public AggregateException aggExcep = new AggregateException();
    
        public void whereExceptionOccurs(){
            try{
    
                  //some code
            }catch(Exception e){
    
                  aggExcep.addException(e);
                  //throw aggExcep;
            }  
        }
    }
    

    Call the method addException with the same reference aggExcep wherever you want to(Inside the catch block obviously) suppress any exception. And at the end explicitly throw aggExcep using 'throw' keyword where ever you want to.

    The

    void addSuppressed(Throwable exception)

    is a predefined method of Throwable class which appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

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

    You can't throw two exceptions. I.e. you can't do something like:

    try {
        throw new IllegalArgumentException(), new NullPointerException();
    } catch (IllegalArgumentException iae) {
        // ...
    } catch (NullPointerException npe) {
        // ...
    }
    

    Alternative 1: Exception A is caused by exception B

    You could nest exceptions using the cause-constructor to do the following:

    try {
        Exception ex1 = new NullPointerException();
    
        // Throw an IllegalArgumentException that "wraps" ex1
        throw new IllegalArgumentException(ex1);
    } catch (IllegalArgumentException iae) {
        // handle illegal argument...
        throw iae.getCause(); // throws the cause (the NullPointerException)
    }
    

    Good article on chained exceptions: Programming.Guide: Chained Exceptions

    Alternative 2: Use suppressed exception

    One exception can suppress another exception.

    try {
        Exception ex1 = new NullPointerException();
    
        // Throw an IllegalArgumentException that "suppresses" ex1
        IllegalArgumentException ex2 = new IllegalArgumentException();
        ex2.addSuppressed(ex1);
        throw ex2;
    } catch (IllegalArgumentException iae) {
        // handle illegal argument...
        ... iae.getSuppressed() ... // get hold of the suppressed exceptions
    }
    

    Good article on suppressed exceptions: Programming.Guide: Suppressed Exceptions

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

    The pattern described by Andreas_D is definitely useful whenever you're handling, say, the server-side compilation of a user-provided file and want to report back the errors.

    For example, you might have a CompilationException which gets generated if the resource fails to compile. Compiling might mean any number of things. For example, you might evaluate the text inside of a file that an end user uploads, parse out tokens, check for syntax errors and determine whether the file is valid. At the end, the thing is either valid or it is invalid and you want to hand back a proper CompilationException to propagate back up the call stack.

    Like Andreas describes, you can have an add() method that lets you add compilation issues to your exception. Those issues don't have to be Exceptions themselves, but that's up to you. It often helps to stick to a single exception framework so that you can use the same validation logic in multiple places.

    At any rate, what you want is a single CompilationException falling back through the call stack because that tells the framework that the thing did not compile. If anyone up the chain wants to know why, then they can get at the underlying issues with a call to, say, getCauses().

    It's also useful from a UI perspective. That information sticking around on the Exception can be properly handled before going back over the wire so that you can give your end user some information as to why the compilation failed.

    0 讨论(0)
  • 2020-12-28 14:03

    A method can throw one of several exceptions. Eg:

     public void dosomething() throws IOException, AWTException {
          // ....
     }
    

    This signals that the method can eventually throw one of those two exceptions (and also any of the unchecked exceptions). You cannnot (in Java or in any language AFAIK) throw simultaneously two exceptions, that would not make much sense.

    You can also throw a nested Exception, which contains inside another one exception object. But that would hardly count that as "throwing two exceptions", it just represents a single exception case described by two exceptions objects (frequently from different layers).

    0 讨论(0)
  • 2020-12-28 14:03

    You can have the possibility of throwing multiple different exceptions. For example:

    if (obj == null)
        throw new NullPointerException();
    
    if (some other case)
        throw new IllegalArgumentException();
    
    if (this == this)
        throw new IOException();
    

    This code may throw multiple different exceptions, but this can never happen at the same time.

    0 讨论(0)
提交回复
热议问题