异常处理不当:导致Java应用程序崩溃案例
在Java编程中,异常处理是防止程序因为意外情况(如除以零、文件未找到等)而崩溃的重要手段。下面我们将通过一个具体的案例来说明异常处理不当可能带来的问题。
案例描述:
假设有一个简单的Java程序,用户输入两个整数,然后计算这两个数的和。为了处理可能的异常,我们添加了以下异常处理代码:
import java.util.Scanner;
public class SumCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter the first integer:");
int num1 = scanner.nextInt();
System.out.println("Enter the second integer:");
int num2 = scanner.nextInt();
// Calculate sum
int sum = num1 + num2;
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
} catch (Exception e) {
System.err.println("An error occurred while calculating the sum.");
e.printStackTrace();
} finally {
scanner.close();
}
}
}
问题出现:
然而,当用户输入非整数时(例如,一个空格或一个字母),程序并没有捕获这个异常。在这种情况下,程序会崩溃。
解决办法:
在上述案例中,我们应当添加对InputMismatchException
的捕获,这样当用户输入不合法数据时,程序能够正确处理并避免崩溃:
import java.util.Scanner;
public class SumCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter the first integer:");
int num1 = scanner.nextInt();
if (num1 <= 0) {
throw new IllegalArgumentException("The first integer must be positive.");
}
System.out.println("Enter the second integer:");
int num2 = scanner.nextInt();
// Calculate sum
int sum = num1 + num2;
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
} catch (IllegalArgumentException | InputMismatchException e) {
System.err.println("An error occurred while calculating the sum.");
if (e instanceof IllegalArgumentException) {
e.printStackTrace();
} else {
e.printStackTrace().addSuppressed(new RuntimeException("Unexpected exception caught.", e.getCause()))); // Add suppressed cause for InputMismatchException
}
} finally {
scanner.close();
}
}
}
通过以上改进,当用户输入非法数据时,程序将能够正确处理并避免崩溃。
还没有评论,来说两句吧...