zoukankan      html  css  js  c++  java
  • 26 自定义异常

    案例

    设置一个异常:非法年龄异常,当Person类的setAge方法检测到参数age的值大于100或小于0时,抛出该异常。

    需要注意的地方

    • 自定义异常继承自Exception或RuntimeException
    • 异常后显示的自定义信息定义在构造方法中,如下面代码
    • 异常要声明在方法后面:方法() throws 自定义异常名
    • 抛出异常的代码为:throw new 自定义异常名("需要显示的错误信息");
    • 对可能出现自定义异常的方法进行trycatch

    自定义异常

    写一个异常类,继承自Exception或RuntimeException,其中,继承自RuntimeException的异常无需向上声明。

    以下的重写方法可以直接右键-》sround-》generate Constructors from superClass-》全选-》确定

    package exception;
    /**
     * 非法年龄异常
     * @author TEDU
     *
     */
    public class IllegalAgeException  extends Exception{
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	public IllegalAgeException() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	public IllegalAgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    		super(message, cause, enableSuppression, writableStackTrace);
    		// TODO Auto-generated constructor stub
    	}
    
    	public IllegalAgeException(String message, Throwable cause) {
    		super(message, cause);
    		// TODO Auto-generated constructor stub
    	}
    
    	public IllegalAgeException(String message) {
    		super(message);
    		// TODO Auto-generated constructor stub
    	}
    
    	public IllegalAgeException(Throwable cause) {
    		super(cause);
    		// TODO Auto-generated constructor stub
    	}
    
    }
    

      

    Person类

    在setAge时做处理,当不符合年龄范围则new并抛出异常

    package exception;
    
    public class Person {
    	int age;
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) throws IllegalAgeException {//注意这里要抛出
    		if(age>100||age<0) {
    			throw new IllegalAgeException("年龄非法");//这里要new
    		}
    		this.age = age;
    	}
    	
    }

      

    测试类

    当输入:p.setAge()时,由于这个方法抛出了异常,必须处理或向上声明。这里我们直接处理它,用try-catch:

    package exception;
    
    public class ThrowDemo {
    	public static void main(String[] args) {
    		Person p  = new Person();
    		try {
    			p.setAge(1000);
    		} catch (IllegalAgeException e) {
    			e.printStackTrace();
    			System.out.println(e.getMessage());
    		}
    	}
    }
    

      

    另外我们可以在catch中使用e.getMessage()获取错误提示信息,如上面的自定义异常,获取到的字符串就是:

    "年龄非法"
  • 相关阅读:
    好用的镜头站下载工具
    300+Jquery, CSS, MooTools 和 JS的导航菜单资源
    股票入门2
    MEF学习笔记(6):出口和元数据
    MEF学习笔记(5):迟延加载导出部件
    WinForm控件复杂数据绑定常用数据源(如:Dictionary)(对Combobox,DataGridView等控件DataSource赋值的多种方法)
    wpf 多线程绑定控件
    HTTP 错误 404.2 Not Found 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面
    ADODB.Stream 错误 '800a0bbc' 写入文件失败。
    'System.Windows.StaticResourceExtension' threw an exception
  • 原文地址:https://www.cnblogs.com/Scorpicat/p/11973145.html
Copyright © 2011-2022 走看看