Java 抛异常的两种方法
程序员文章站
2024-02-09 18:14:10
...
import java.io.*;
public class EmployeeTest{
EmployeeTest(){
}
public void Test1(int x) throws ArrayIndexOutOfBoundsException,ArithmeticException{
System.out.println(x);
if(x == 0){
System.out.println("没有异常");
return;
}
//数据越界异常
else if (x == 1){
int[] a = new int[3];
a[3] = 5;
}
//算术异常
else if (x == 2){
int i = 0;
int j = 5/0;
}
}
public void Test2(int x){
try {
System.out.println(x);
if(x == 0){
System.out.println("没有异常");
return;
}
//数据越界异常
else if (x == 1){
int[] a = new int[3];
a[3] = 5;
}
//算术异常
else if (x == 2){
int i = 0;
int j = 5/0;
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
EmployeeTest abc = new EmployeeTest();
abc.Test1(0);
abc.Test2(1);
}
}