在 Java 里,异常和错误都属于 Throwable
类的子类,它们用于处理程序里出现的不正常状况。下面为你详细介绍 Java 异常和错误的相关知识。
IOException
、SQLException
等都属于受检查异常。NullPointerException
、ArrayIndexOutOfBoundsException
等。OutOfMemoryError
、StackOverflowError
等。Java 提供了 try-catch-finally
语句块来处理异常,具体语法如下:
try {
// 可能会抛出异常的代码
} catch (ExceptionType1 e1) {
// 处理 ExceptionType1 类型的异常
} catch (ExceptionType2 e2) {
// 处理 ExceptionType2 类型的异常
} finally {
// 无论是否发生异常,都会执行的代码
}
下面是一个简单的示例:
public class ExceptionExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // 会抛出 ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常: " + e.getMessage());
} finally {
System.out.println("无论是否发生异常,这里的代码都会执行。");
}
}
}
若方法无法处理某个异常,可使用 throw
关键字抛出异常,同时使用 throws
关键字在方法签名中声明该异常。示例如下:
public class ThrowExample {
public static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("除数不能为零");
}
int result = a / b;
System.out.println("结果: " + result);
}
public static void main(String[] args) {
try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("捕获到异常: " + e.getMessage());
}
}
}
你可以自定义异常类,只需继承 Exception
或 RuntimeException
类。下面是一个自定义异常的示例:
// 自定义异常类
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用自定义异常的类
public class CustomExceptionExample {
public static void checkAge(int age) throws CustomException {
if (age < 0) {
throw new CustomException("年龄不能为负数");
}
System.out.println("年龄合法: " + age);
}
public static void main(String[] args) {
try {
checkAge(-5);
} catch (CustomException e) {
System.out.println("捕获到自定义异常: " + e.getMessage());
}
}
}
try-catch-finally
语句块进行处理。throw
关键字抛出异常,使用 throws
关键字在方法签名中声明异常。Exception
或 RuntimeException
类。通过上述内容,你应该对 Java 异常和错误有了更深入的理解。在实际开发中,合理运用异常处理机制能够增强程序的健壮性和可维护性。