java异常的匹配

发表于: java/j2ee | 作者: | 日期: 2010/11/28 11:11

(1)异常是按照catch的书写顺序进行匹配的。找到匹配的处理程序后,它就认为异常将得到处理,然后就不在查找。

示例代码1:


package com.darkmi.exceptionstudy;

public class ExceptionTest {
public static void main(String[] args) {

try {
throw new TwoException();
} catch (TwoException twoE) {
twoE.printStackTrace();
} catch (OneException oneE) {
oneE.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

}

class OneException extends Exception{
}

class TwoException extends OneException{
}

在Eclipse中编辑该代码,Eclipse的智能提示功能已经给出warning:

Unreachable catch block for OneException. Only more specific exceptions are thrown and handled by previous catch block(s).

(2)查找的时候并要求抛出的异常同异常处理程序(即catch代码段)所声明的异常完全匹配,派生类的对象也可以匹配处理程序中声明的基类。

示例代码2:


package com.darkmi.exceptionstudy;

public class ExceptionSearch {
public static void main(String[] args) {
try {
throw new TwoException();
} catch (OneException oneE) {
oneE.printStackTrace();
}
}

}

class OneException extends Exception {
}

class TwoException extends OneException {
}

: https://blog.darkmi.com/2010/11/28/1428.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.