Java编程异常处理是一项重要的技术,用于捕获和处理在程序运行时可能发生的错误。Java提供了多种机制来处理异常,主要包括try-catch语句、try-catch-finally语句、try-with-resources语句以及自定义异常类
对异常处理思路:
1,声明异常时,建议声明更为具体的异常,这样可以处理的更具体
2,声明几个异常,就对应几个catch块, 如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面
使用catch块多异常处理,示例1:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("空指针异常: " + e.getMessage());
} catch (Exception e) {
System.out.println("捕获到一般异常: " + e.getMessage());
}
System.out.println("程序继续运行");
}
}
使用catch块多异常处理,示例2:
class Demo
{
int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int []arr = new int [a];
System.out.println(arr[4]); //第一处异常
return a/b; //第二处异常
}
}
class ExceptionDemo
{
public static void main(String[]args) //throws Exception
{
Demo d = new Demo();
try
{
int x = d.div(4,0);
//int x = d.div(5,0);
//int x = d.div(4,1);
System.out.println("x="+x);
}
catch (ArithmeticException e)
{
System.out.println(e.toString());
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}
catch (Exception e)
{
System.out.println(e.toString());
}
System.out.println("Over");
}
}

7476

被折叠的 条评论
为什么被折叠?



