Java – throw multiple exceptions from a method
•
Java
How to throw multiple exceptions from one method at a time? Example:
public void doA() throws Exception1,Exception2{ throw new Exception1("test1"); throw new Exception2("test2"); }
How to do such work?
Edit: a condition throws exception1 and exception2 probably? This is just a demo file for testing exceptions thrown
Solution
You should check whether there is something right in the method that throws the exception Here is an example:
public void doA() throws Exception1,Exception2 { if (<some unexpected condition>) { throw new Exception1("test1"); } if (<another unexpected condition>) { throw new Exception2("test2"); } //rest of the implementation... }
If you mean how to throw several exceptions at the same time, it is impossible, because throwing exceptions will destroy the execution of the method (similar to return) You can only throw one exception at a time
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码