`
hibernater
  • 浏览: 134636 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java自定义异常

阅读更多
在自定义异常时,应如何派生?必须在Throwable类层次结构中派生,否则将不能在应用程序中传播异常。另外,不能从Throwable直接派生。Throwable为两类主要问题(ExceptionError)提供行为基础,不能为这棵继承树定义新分支。一般也不要直接继承Error或其任何子类,因为自定义异常通常不符合错误标准(即适当应用程序不应试图捕获的严重问题)
一般我们自己定义的异常分为检查型异常checked(编译时异常:Exception和它的子类)和非检查型异常non-checked(运行时异常:RuntimeException和它的子类)。
以下两个例子表明的区别是:除非派生一个非检测异常类(RuntimeExceptionError),否则调用方法的任何对象随后将按照“处理或声明”规则解决该异常。
RuntimeException:
package baal.exception;

public class BaalException extends RuntimeException {

	 
	public BaalException() {
	}

	public BaalException(String message) {

		super(message);

	}
}
 
 
package baal.exception;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Tester tester=new Tester();
		 
			tester.getNo1("baal");
		 
	}

}
package baal.exception;

public class Tester {
	
	 

	public void getNo1(String a)  {
		if("baal".equals(a))throw new BaalException("String is baal");
	}

}

  

运行控制台信息:

Exception in thread "main" baal.exception.BaalException: String is baal
                                                          at baal.exception.Tester.getNo1(Tester.java:8)
                                                          at baal.exception.Main.main(Main.java:12

 

 

 

Exception:

 

 

package baal.exception;

public class BaalException extends  Exception {

	 
	public BaalException() {
	}

	public BaalException(String message) {

		super(message);

	}
}

 

 

package baal.exception;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Tester tester=new Tester();
		 
			try {
				tester.getNo1("baal");
			} catch (BaalException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 
	}

}

 

package baal.exception;

public class Tester {
	
	 

	public void getNo1(String a) throws BaalException  {
		if("baal".equals(a))throw new BaalException("String is baal");
	}

}

 

 

运行控制台的结果:

 

 

 baal.exception.BaalException: String is baal
                at baal.exception.Tester.getNo1(Tester.java:8)
                at baal.exception.Main.main(Main.java:13)

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics