Java异常处理机制:捕获与抛出示例案例
在Java编程中,异常处理机制是确保程序在出现错误或异常情况时能够正常运行的重要手段。主要包括两种操作:捕获(catch)和抛出(throw)。
捕获异常:
try {
// 有可能产生异常的代码
int divisionByZero = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("捕获到除以零的异常: " + e.getMessage());
}
在这个例子中,我们尝试执行
5 / 0
,这会抛出一个ArithmeticException
。然后我们在catch
块中捕获这个异常,并打印出异常的消息。抛出异常:
public class ExceptionExample {
public void throwException() throws Exception {
// 在这里产生异常的代码
String invalidInput = "Hello, World!";
if (invalidInput.isEmpty()) {
throw new IllegalArgumentException("Invalid input");
}
}
public static void main(String[] args) {
try {
ExceptionExample example = new ExceptionExample();
example.throwException();
} catch (IllegalArgumentException e) {
System.out.println("捕获到输入无效的异常: " + e.getMessage());
} catch (Exception anyException) {
System.out.println("捕获到任何类型的异常: " + anyException);
}
}
}
在这个例子中,我们在
throwException()
方法中产生一个IllegalArgumentException
。然后在main()
方法中的try-catch
块中捕获这个异常,并打印出异常的消息。
总结:Java的异常处理机制通过捕获和抛出异常来确保程序在遇到错误时能够保持稳定运行。
还没有评论,来说两句吧...