📜  处理异常方法的Java程序

📅  最后修改于: 2022-05-13 01:55:30.650000             🧑  作者: Mango

处理异常方法的Java程序

破坏程序正常流程的不太可能发生的事件称为异常。 Java异常处理是一种面向对象的异常处理方式。当程序执行过程中发生错误时,会创建一个异常对象,其中包含有关异常层次结构的信息以及其他调试必不可少的信息。

异常类型:

  • 检查异常
  • 未经检查的异常

处理异常:

示例 1:

我们被要求根据班级的平均表现向学校的每个班级分发巧克力。我们有两个等长的数组。第一个数组包含每个盒子中的巧克力数量,第二个数组包含每个班级的学生人数。如果一个班级的平均表现低于标准,他们就没有资格获得任何巧克力,盒子里的巧克力数量将平均分配给所有其他盒子。每个班级分别得到一个巧克力盒。

所以要划分班级学生的巧克力数量,我们必须用巧克力的数量除以班级学生的数量。假设一个班级的平均表现低于标准,他们不会得到任何巧克力,并且该部分的学生人数为零。在解决上述问题时,可能会面临被零除的异常。为了克服它,我们可以使用 try-catch 块并要求用户更新给定的信息。

下面是上述方法的实现:

Java
// Java program to demonstrate Arithmetic Exception
  
class GFG {
    public static void main(String[] args)
    {
        // Number of chocolates in each box
        int chocolates[] = { 106, 145, 123, 127, 125 };
  
        // Number of students in class
        int students[] = { 35, 40, 0, 34, 60 };
  
        // Number of chocolates given to each student of a
        // particular class
        int numChoc[] = new int[5];
        try {
            for (int i = 0; i < 5; i++) {
                // Calculating the chocolates
                // to be distributed
                numChoc[i] = chocolates[i] / students[i];
            }
        }
        // Catching Divide by Zero Exception
        catch (ArithmeticException error) {
            System.out.println("Arithmetic Exception");
            System.out.println(error.getMessage()
                               + " error.");
        }
    }
}


Java
// Java Program to Handle Various Exceptions
  
class GFG {
    public static void main(String[] args)
    {
        // Array1 Elements
        int[] array1 = { 2, 4, 6, 7, 8 };
  
        // Array2 Elements
        int[] array2 = { 1, 2, 3, 4, 5 };
        // Initialized to null value
        int[] ans = null;
        try {
            for (int i = 0; i < 5; i++) {
                ans[i] = array1[i] / array2[i];
                // Generates Number Format Exception
                Integer.parseInt("Geeks for Geeks");
            }
        }
        catch (ArithmeticException error) {
            System.out.println(
                "The catch block with Arithmetic Exception is executed");
        }
        catch (NullPointerException error) {
            System.out.println(
                "The catch block with Null Pointer Exception is executed");
        }
        catch (ArrayIndexOutOfBoundsException error) {
            System.out.println(
                "The catch block with Array Index Out Of Bounds Exception is executed");
        }
        catch (NumberFormatException error) {
            System.out.println(
                "The catch block with Number Format Exception is executed");
        }
        // Executes when an exception which
        // is not specified above occurs
        catch (Exception error) {
            System.out.println(
                "An unknown exception is found "
                + error.getMessage());
        }
  
        // Executes after the catch block
        System.out.println("End of program");
    }
}


输出
Arithmetic Exception
/ by zero error.

示例 2:

Java有一个强大的错误处理机制,允许我们使用不同的 catch 块在一个 try 块中处理多个异常。 Java中的 Catch 块就像 if-else 语句,当异常发生时它会被激活。发生异常时,程序将生成的异常对象与 catch 块中指定的异常进行比较。程序检查第一个 catch 块,然后移动到其他块,依此类推,直到匹配生成的异常。如果没有匹配到 catch 块,程序将停止,并在控制台上抛出异常。

在try块中产生异常后,控制权立即转移到catch块,try块将不再执行。通过更改数组的大小或将 array2 中的特定元素更改为零或初始化答案数组来修补以下代码,以更好地理解Java异常处理。

下面的代码说明了如何在单个 try 块中处理各种类型的错误。

Java

// Java Program to Handle Various Exceptions
  
class GFG {
    public static void main(String[] args)
    {
        // Array1 Elements
        int[] array1 = { 2, 4, 6, 7, 8 };
  
        // Array2 Elements
        int[] array2 = { 1, 2, 3, 4, 5 };
        // Initialized to null value
        int[] ans = null;
        try {
            for (int i = 0; i < 5; i++) {
                ans[i] = array1[i] / array2[i];
                // Generates Number Format Exception
                Integer.parseInt("Geeks for Geeks");
            }
        }
        catch (ArithmeticException error) {
            System.out.println(
                "The catch block with Arithmetic Exception is executed");
        }
        catch (NullPointerException error) {
            System.out.println(
                "The catch block with Null Pointer Exception is executed");
        }
        catch (ArrayIndexOutOfBoundsException error) {
            System.out.println(
                "The catch block with Array Index Out Of Bounds Exception is executed");
        }
        catch (NumberFormatException error) {
            System.out.println(
                "The catch block with Number Format Exception is executed");
        }
        // Executes when an exception which
        // is not specified above occurs
        catch (Exception error) {
            System.out.println(
                "An unknown exception is found "
                + error.getMessage());
        }
  
        // Executes after the catch block
        System.out.println("End of program");
    }
}
输出
The catch block with Null Pointer Exception is executed
End of program