Java 中的错误处理





5.00/5 (10投票s)
开始学习 Java 编程的错误和异常处理
错误可以分为两类
- 编译时错误
- 运行时错误
编译时错误
编译时错误也称为设计时错误。 这可能是语法错误,也可能是代码设计中的错误。 这种类型的错误在编写Java代码时,可以在专门为编写Java代码而开发的高级编辑器或IDE中轻松捕获。
例如,让我们以声明一个整数变量为例。
public static void main(String[] args) {
int num1 = 50
System.out.println("The number is " + num1);
}
现在,如果我在我的IDE中输入此代码,或者如果我编译上面的Java代码文件,它将立即在第2行显示一个错误指示符,即int num1 = 50
因为该行存在语法错误。 我没有用分号“;
”结束语句。 因此,当尝试编译上面的代码时,我将收到一个编译错误。 开发人员可以轻松转到第2行并修复错误。
让我们从文件处理中再举一个例子。
public static void main(String[] args) {
// The program assumes the file path as a parameter or argument.
// Get the file path into the variable
String fileName=null;
if(args!=null && args.length>0){
fileName=args[0];
}
// Read the file and write some text into the file.
File file = new File (fileName);
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file) );
writer.write( "Hello World" );
writer.close();
}
现在,上面的代码看起来很好,没有任何语法错误。 但是,Java将无法再次编译上面的代码。 尽管代码中没有语法错误,但是代码结构中存在一些异常。 试想一下,如果您在程序中寻找的文件不存在于给定位置。
如果您尝试编译此代码,它将为您提供一些异常,指出应捕获或处理FileNotFoundException
和IOException
。
运行时错误
运行时错误称为逻辑错误,无法在编辑器中或编译源代码时捕获。 Java将能够成功编译源代码并生成二进制.class文件,因为对于编译器来说,一切看起来都很好,无论是在语法上还是在结构上。
这些错误发生在运行时,当应用程序实际上由最终用户执行时。
运行时错误通常是由于您的代码逻辑中的某些错误或提供给应用程序的无效输入(应用程序未被期望或设计为接收)而发生的。这些错误可能会在运行时破坏或崩溃您的应用程序逻辑。
例如,让我们举一个简单的算术运算的例子。
public static void main(String[] args) {
if(args!=null && args.length>1){
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1/num2;
System.out.println(num1 + "/" + num2 + " = " + result);
}
}
上面的程序接受两个数字作为参数,并将第一个数字除以第二个数字。
Java将编译上面的源代码,而不会出现任何编译错误,并生成.class文件。
让我们考虑一个用户使用0
作为第二个参数运行应用程序的情况。
然后,它将向用户显示一个运行时错误,显示“除以零”,因为任何除以零都是未定义的。 它将在整数类型变量除以零的行上返回以下算术异常,即int result = num1/num2;
Exception in thread "main" java.lang.ArithmeticException:
因此,开发人员应始终在代码中采取预防措施,以处理运行时可能发生的异常。 这将防止他们的程序崩溃,即使应用程序程序的某些部分未能执行,该应用程序也能完美运行。
处理异常
可以使用“try
-catch
”块来处理异常。 Try
块包含您怀疑可能出现异常的代码。 Catch
块包含异常的替代方法。 如果在try
块中发生任何异常,则控制权将跳转到catch
块,您可以在其中向用户输出一些自定义消息或执行一些替代方法。
让我们看看如何通过使用try
-catch
块来处理第一个示例(即“除以零”)中的运行时异常。
public static void main(String[] args) {
if(args!=null && args.length>1){
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1/num2;
System.out.println("The result is " + result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
同样,在上面的代码中可能还会发生另一个异常,例如,如果用户传递了两个string
而不是两个数字。
因此,如果您可以对异常进行具体说明,那就更好了。
public static void main(String[] args) {
if(args!=null && args.length>1){
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1/num2;
System.out.println(num1 + "/" + num2 + " = " + result);
}
catch (NumberFormatException e) {
// If the arguments cannot not parsed as integers.
System.out.println("Enter numeric values only.");
}
catch (ArithmeticException e) {
// If the arithmetic operation (divide by) is failed.
System.out.println("Undefined result.");
}
catch (Exception e) {
// If any other exception occurred.
System.out.println(e.getMessage());
}
}
}
让我们看看如何通过使用try
-catch
块来处理第二个示例(即“文件处理示例”)中的编译时异常。
public static void main(String[] args) {
File file = new File ("MyTextFile.txt");
try {
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file) );
// Do your stuffs here...
// I will just write steps to write some text into the file.
writer.write( "Hello World" );
writer.close();
} catch (FileNotFoundException e) {
// If file not found then control goes here
System.out.println("File not found");
} catch (IOException e) {
// Catch block for other IO Exceptions;
}
}
Java 7通过编写更少的代码使其变得更加容易。
这将在try
块的末尾自动关闭流,您不必编写关闭文件的步骤。
try ( OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)) ) {
writer.write( "Hello World" );
} catch (FileNotFoundException e) {
// If file not found then control goes here
System.out.println("File not found");
} catch (IOException e) {
// Catch block for other IO Exceptions;
}
这些是有关处理Java编程中的编译时和运行时错误的一些代码示例。 希望这可以帮助您开始在Java中进行异常处理。