throws的方式处理异常

跟風遠走 提交于 2019-12-12 06:23:45

throws的方式处理异常

  • A:throws的方式处理异常
    • 定义功能方法时,需要把出现的问题暴露出来让调用者去处理。
    • 那么就通过throws在方法上标识。
  • B:案例演示
    • 举例分别演示编译时异常和运行时异常的抛出
    • 编译时异常的抛出必须对其进行处理,否则报错
    • 运行时异常的抛出可以处理也可以不处理
package com.heima.exception;

public class Demo06_Exception {

	public static void main(String[] args) throws Exception {
		Person p = new Person();
		p.setAge(17);
		System.out.println(p.getAge());
	}
}

class Person {
	private String name;
	private int age;
	
	public Person() {
		super();
	}
	
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) throws Exception{
		if (age > 0 && age <= 150) {
			this.age = age;
		} else {
			//方法中如果抛出一个运行时异常时,在方法上不用做任何声明.
			//如果在方法中抛出一个编译时异常,在方法上就必须做声明,否则报错.
			throw new Exception("年龄非法");
		}
	}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!