Java 异常 - Try...Catch
Java 异常
在执行 Java 代码时,可能会发生各种错误:程序员编写的编码错误、由于输入错误导致的错误,或者其他无法预见的情况。
当发生错误时,Java 通常会停止执行并生成错误消息。这在技术上称为:Java 将**抛出异常**(抛出一个错误)。
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)
注意: 当您尝试访问不存在的索引号时,会发生 ArrayIndexOutOfBoundsException
。
如果发生错误,我们可以使用 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
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.");
}
}
}
输出将是:
发生了错误。
The 'try catch' is finished.
throw 关键字
throw
语句允许您创建自定义错误。
throw
语句与**异常类型**一起使用。Java 中有许多可用的异常类型:ArithmeticException
、FileNotFoundException
、ArrayIndexOutOfBoundsException
、SecurityException
等等。
示例
如果 age 小于 18,则抛出异常(打印 "Access denied")。如果 age 为 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)
如果 age 是 20,您将**不会**收到异常
错误和异常类型参考
有关不同错误和异常类型的列表,请访问我们的 Java 错误和异常类型参考。