例外是在程序执行期间发生的事件,该事件破坏了程序指令的正常流程。当方法内发生异常情况时,将Exception引发对象。该对象包含有关发生的错误或异常问题的信息。
创建异常对象并将其交给运行时系统称为抛出异常。如果要处理发生的异常,可以在处理它们的方法中包括三种代码块。try,catch和finally块。
该try块包含可能引起一个或多个异常的代码
该catch块包含旨在处理可能在关联的try块中引发的特定类型异常的代码
finally始终在块中的代码在方法结束之前执行,而不管try块中是否抛出任何异常。
package org.nhooo.example.fundamental;
public class ExceptionHandlerExample {
public static void main(String[] args) {
int x = 1, y = 0, z = 0;
try {
// 除以0将引发异常
z = ExceptionHandlerExample.divide(x, y);
System.out.println("z = " + z);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally block is always executed.");
}
}
/**
* Divide the given first number by the second number.
*
* @param x the first number.
* @param y the second number.
* @return the result of division.
* @throws RuntimeException when an exception occurs.
*/
private static int divide(int x, int y) throws RuntimeException {
return x / y;
}
}这是我们运行程序时发生的情况:
java.lang.ArithmeticException: / by zero at org.nhooo.example.fundamental.ExceptionHandlerExample.divide(ExceptionHandlerExample.java:30) at org.nhooo.example.fundamental.ExceptionHandlerExample.main(ExceptionHandlerExample.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110) Finally block is always executed.