Throwing multiple exceptions in Java

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

Is there any way to throw multiple exceptions in java?

11条回答
  •  暖寄归人
    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.

提交回复
热议问题