Java 异常处理
Java 异常
在执行 Java 代码时,可能会发生不同的错误:程序员的编码错误、错误输入导致的错误或其他不可预见的事情。
当发生错误时,Java 通常会停止并生成错误消息。技术术语是:Java 将抛出异常(throw an error)。
Java try 与 catch
try
语句允许您定义一个代码块,以便在执行时对其进行错误测试。
catch
语句允许您在 try 块中发生错误时定义要执行的代码块。
try
和 catch
关键字成对出现:
语法
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
思考下面的例子:
这段代码将产出一个错误,因为 myNumbers[10] 不存在。
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
输出将是这样的:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
10 at Main.main(Main.java:4)
10 at Main.main(Main.java:4)
如果发生错误,我们可以使用 try…catch
来捕获错误并执行一些代码来处理它:
实例
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
结果将为:
Something went wrong.
Finally
不论结果如何,finally
语句都会在 try…catch
之后执行代码:
实例
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
结果将为:
Something went wrong.
The 'try catch' is finished.
The 'try catch' is finished.
throw 关键字
throw
语句让您可以创建自定义错误。
throw
语句与 异常类型 一起使用。Java 中有许多可用的异常类型: ArithmeticException
, FileNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, 等等:
实例
如果年龄低于 18 岁,则引发异常(输出 "Access denied")。如果年龄在18岁或以上,请输出 "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
结果将为:
Exception in thread “main” java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
如果 年龄 是 20, 您 不会 得到异常返回:
实例
checkAge(20);
结果将为:
Access granted - You are old enough!