1.throw和throws
throw用于显式地抛出一个异常。
private static void printArr(int[] arr){
if (arr == null){
throw new NullPointerException();
} else {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
throws用于声明一个方法可能会抛出的异常。。
public void myMethod() throws IOException {
// 可能会引发IOException的代码
}
2.try catch
try {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的年纪:");
String name = sc.nextLine();
int age =Integer.parseInt(name);
System.out.println(name);
System.out.println(2/0);
} catch (NumberFormatException e) {
System.out.println("解析错误发生了");
} catch (ArithmeticException e){
System.out.println("数学运算错误发生了");
}
System.out.println("嘿嘿嘿 我是最帅的!");
3.Throwable的成员方法
1.getMessage()
public String getMessage() //返回此throwable的详细消息字符串
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5 };
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
}
//结果是: Index 10 out of bounds for length 5
2.toString()
public String toString()//返回此可抛出的简短描述
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5 };
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e){
System.out.println(e.toString());
}
}
//结果: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5
3. printStackTrace
public void printStackTrace() //把异常的错误信息输出在控制台(字体是红色的)
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5 };
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
System.out.println("我的牛牛很大");
}
/*运行结果:
D:\JavaDevelop\Java\java17\bin\java.exe "-javaagent:D:\JavaDevelop\idea\IntelliJ IDEA 2024.1.4\lib\idea_rt.jar=51228:D:\JavaDevelop\idea\IntelliJ IDEA 2024.1.4\bin" -Dfile.encoding=UTF-8 -classpath D:\JavaWorkSpace\xing-xi-guan-li\out\production\ExceptionDemo1 ExceptionDemo1.ExceptionDemo1
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5
at ExceptionDemo1.ExceptionDemo1.main(ExceptionDemo1.java:9)
我的牛牛很大
*/