使用场景:throw
和 throws
关键字都是用于抛出异常
throw
作用:抛出java已有的错误类
位置:在方法内
实例代码
package exception;
public class Test02 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// Ctrl+Alt+t 代码块包裹
try {
if (b==a) {
throw new ArithmeticException();
}
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public void test(int a, int b) {
// 主动抛出异常一般在方法里用 throw
if (b==a) {
throw new ArithmeticException();
}
}
}
throws
作用:把 throw
的抛出对象从java已有异常类改成“自定义”异常类
位置:函数头尾端 public void test() throws MyException {}
实例程序:
1.自定义异常类
package exception;
public class MyException extends Exception{
//传递数字>10
private final int detail;
public MyException(int a){
this.detail = a;
}
//toString
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
2.实现类
package exception;
public class MyExceptionImp {
private int num;
public MyExceptionImp(int num) {
this.num = num;
}
// 如果num超过10,则要改变num的值,这里用取余运算
public void changeVal(){
this.num = this.num%10;
}
public void printVal(){
System.out.println("changed num is: " + num);;
}
// 可能存在异常的方法
public void test() throws MyException {
System.out.println("传递的参数为"+num);
if (this.num>10) {
throw new MyException(num); // 抛出异常
}
System.out.println("OK");
}
public static void main(String[] args) {
MyExceptionImp myExceptionImp = new MyExceptionImp(11);
// System.out.println(Integer.MAX_VALUE);
// System.out.println(Character.isDigit(3));
while (true) {
try {
myExceptionImp.test();
break;
} catch (MyException e) {
// e.printStackTrace(); // 这个方法有什么用
System.out.println("MyException => "+e); // 这个e走的就是 toString() 方法
// 增加一些拯救的代码
System.out.println("==========");
myExceptionImp.changeVal();
myExceptionImp.printVal();
}
}
}
}
网友评论