throw和throws
package com.yuzhenc.exception;
import java.util.Scanner;
public class Test04 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("请输入除数:");
int num1 = sc.nextInt();
System.out.print("请输入被除数:");
int num2 = sc.nextInt();
try {
System.out.println(num1/num2);
}catch (ArithmeticException e) {
throw new Exception();
}
}
}
区别 | throw | throws |
---|
位置不同 | 方法内部 | 方法签名处,方法声明处 |
内容不同 | +异常类对象 | +异常的类型,多个类型,分隔 |
作用不同 | 异常出现的源头,制造异常 | 声明异常,要么自己处理,要么向外抛出 |
重载与重写异常
package com.yuzhenc.exception;
public class Test05 {
public void a() throws Exception {}
public void a(int a) throws ArrayIndexOutOfBoundsException {}
}
class Test06 extends Test05 {
public void a() throws ArithmeticException {}
}
自定义异常类
- 如果继承的是运行时异常,那么在使用的时候无需额外处理;
- 如果继承的是检查异常,那么使用的时候需要try-catch捕获或者throws向上抛;
package com.yuzhenc.exception;
public class Test07 {
public static void main(String[] args) throws MyException,MyException1 {
if(1 == 2) {
throw new MyException("发生了检查异常");
} else {
throw new MyException1("发生了运行时异常");
}
}
}
class MyException extends Exception {
public MyException() {}
public MyException(String message) {
super(message);
}
}
class MyException1 extends RuntimeException {
public MyException1() {}
public MyException1(String message) {
super(message);
}
}