1.异常定义
2.异常的种类
3.自定义异常:
使用自定义异常的优点:
4.系统异常与自定义的区别
若一个方法可能抛出系统异常则该方法不用显示的throws系统异常。
若一个方法可能抛出自定义的异常则必须要用throws抛出该方法可能抛出的异常,否则不能通过编译。
public class ExceptionTest {
//抛出系统异常
public void exceptiontest1() throws NumberFormatException{
int a = Integer.parseInt("10");
}
public void checkAge(int age) throws MyException {
if(age < 0){
throw new MyException("年龄不能为负");
}
}
public static void main(String[] args) {
ExceptionTest test1 = new ExceptionTest();
try {
test1.exceptiontest1();
test1.checkAge(-1);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
} catch (MyException e){
System.out.println("原因:" + e.getMessage());
}
}
//自定义异常
public class MyException extends Exception {
private static final long serialVersionUID = 1L;
private String name;
public MyException(String name) {
this.name = name;
}
public String getMessage() {
return this.name;
}
}
}