异常处理不当:导致Java应用程序崩溃案例

原创 男娘i 2024-09-20 01:42 184阅读 0赞

在Java编程中,异常处理是防止程序因为意外情况(如除以零、文件未找到等)而崩溃的重要手段。下面我们将通过一个具体的案例来说明异常处理不当可能带来的问题。

案例描述:
假设有一个简单的Java程序,用户输入两个整数,然后计算这两个数的和。为了处理可能的异常,我们添加了以下异常处理代码:

  1. import java.util.Scanner;
  2. public class SumCalculator {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);
  5. try {
  6. System.out.println("Enter the first integer:");
  7. int num1 = scanner.nextInt();
  8. System.out.println("Enter the second integer:");
  9. int num2 = scanner.nextInt();
  10. // Calculate sum
  11. int sum = num1 + num2;
  12. System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
  13. } catch (Exception e) {
  14. System.err.println("An error occurred while calculating the sum.");
  15. e.printStackTrace();
  16. } finally {
  17. scanner.close();
  18. }
  19. }
  20. }

问题出现:
然而,当用户输入非整数时(例如,一个空格或一个字母),程序并没有捕获这个异常。在这种情况下,程序会崩溃。

解决办法:
在上述案例中,我们应当添加对InputMismatchException的捕获,这样当用户输入不合法数据时,程序能够正确处理并避免崩溃:

  1. import java.util.Scanner;
  2. public class SumCalculator {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);
  5. try {
  6. System.out.println("Enter the first integer:");
  7. int num1 = scanner.nextInt();
  8. if (num1 <= 0) {
  9. throw new IllegalArgumentException("The first integer must be positive.");
  10. }
  11. System.out.println("Enter the second integer:");
  12. int num2 = scanner.nextInt();
  13. // Calculate sum
  14. int sum = num1 + num2;
  15. System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
  16. } catch (IllegalArgumentException | InputMismatchException e) {
  17. System.err.println("An error occurred while calculating the sum.");
  18. if (e instanceof IllegalArgumentException) {
  19. e.printStackTrace();
  20. } else {
  21. e.printStackTrace().addSuppressed(new RuntimeException("Unexpected exception caught.", e.getCause()))); // Add suppressed cause for InputMismatchException
  22. }
  23. } finally {
  24. scanner.close();
  25. }
  26. }
  27. }

通过以上改进,当用户输入非法数据时,程序将能够正确处理并避免崩溃。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,184人围观)

还没有评论,来说两句吧...

相关阅读