http://blog.sina.com.cn/s/blog_6b022bc60101cdbv.html[reprint]java in the Order of exception capture (multiple catch)(2012-11-05 09:47:28)
reproduced
Tags: reprint |
Category: Reprint |
Original Address:Exception capture Order in Java (multiple catch)
Leesajava Code
- Import java.io.IOException;
- public class Exceptiontrycatchtest {
- public void DoSomething () throws ioexception{
- System.out.println ("Do somthing");
- }
- public static void Main (string[] args) {
- Exceptiontrycatchtest et = new exceptiontrycatchtest ();
- try {
- Et.dosomething ();
- } catch (Exception e) {
- //
- } catch (IOException e) {
- //
- }
- }
- }
Question: Can the above program be compiled and passed? Why?
Solution: cannot compile through. Because the compile time will be error: has caught the exception java.io.IOException. catch (IOException E) There is an error in this sentence.
Analysis: for try. In the form of catch catch exceptions, there can be more than one catch for an exception capture. In the case of a try inside the exception, he will be based on the occurrence of the exception and catch inside the match (how to match, according to catch block from top to bottom), when it matches a catch block, he went directly into the catch block, followed by a catch block, It does not do any processing, jump directly past, all ignored. If there is finally, go to the finally inside to continue execution. In other words, if there is a matching catch, it ignores all the catch behind the catch. For us this method, the throw is IOException, when executed etct.dosomething (); When, may throw IOException, one but throws IOException, it first enters into catch (Exception e) {} inside , first and Exception match, because Oexceptionextends Exception, according to the principle of polymorphism, IOException is matching Exception, so the program will go into catch (Exception e) {} inside, After entering the first catch, the catch will not be executed, so catch (IOException e) {} will never execute, giving us the previous error: The exception java.io.IOException has been caught.
Summary: In the write exception processing, it is important to put the scope of the exception in the front, the scope of large in the back, exception the root of the exception must be just in the last catch, if placed in front or in the middle, any exception will and exception match, will be reported to have captured ... The error of the exception.
Change from: Javaeye blog
Reproduced Exception capture Order in Java (multiple catch)