Home  >  Article  >  Java  >  Exceptions allow you to handle errors normally

Exceptions allow you to handle errors normally

Susan Sarandon
Susan SarandonOriginal
2024-10-19 14:09:02927browse

Exceções permitem que você trate erros normalmente

Exception handling allows program continuity:

  • Exceptions are used to handle unexpected errors without terminating the program abruptly.
  • When an exception occurs, the program can catch it, handle it, and continue executing normally.

Example of exception being caught:

  • In the example, we try to divide the elements of two arrays.
  • If division by zero occurs, the ArithmeticException exception will be raised and handled, allowing the program to continue.

Code example:

class ExcDemo3 {
    public static void main(String args[]) {
        int numer[] = { 4, 8, 16, 32, 64, 128 };
        int denom[] = { 2, 0, 4, 4, 0, 8 };

        for (int i = 0; i < numer.length; i++) {
            try {
                // Tenta realizar a divisão
                System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i] / denom[i]);
            } catch (ArithmeticException exc) {
                // Captura e trata a exceção de divisão por zero
                System.out.println("Can't divide by Zero!");
            }
        }
    }
}

Program output:

  • The program displays the result of successful divisions and treats divisions as zero, reporting the error without ending execution.
4 / 2 is 2
Can't divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divide by Zero!
128 / 8 is 16

Exceptions are removed after being handled:

  • Each time the loop is executed, the try block is re-evaluated.
  • Exceptions handled previously do not affect future executions.

Benefit:
Exception handling allows the program to handle repeated errors and continue its execution flow smoothly.

Conclusion:
Exception handling allows the program to continue running by handling errors such as division by zero, rather than terminating execution.

The above is the detailed content of Exceptions allow you to handle errors normally. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn