DEV Community

Vidya
Vidya

Posted on

Exception, Exception Handling

Exception
An exception in Java is an unwanted or unexpected event that occurs during the execution of a program, which disrupts the normal flow of instructions.An exception is a runtime error that occurs while the program is running.

Example

          int a = 10; 
          int b = 0;
          System.out.println(a / b);
          --> This code will cause an exception:
              ArithmeticException (division by zero)
Enter fullscreen mode Exit fullscreen mode

Why Do Exceptions Occur?
-> Dividing a number by zero
-> Accessing an invalid array index
-> Trying to open a file that does not exist
-> Invalid user input
-> Network or database issues

Exception Handling
Exception handling in Java is a mechanism used to handle runtime errors (exceptions) so that the program does not crash and continues execution smoothly.

Why Exception Handling?

      --> Without exception handling 
           * Program stops suddenly (crash)

      --> With exception handling
           *Program handles error and continues
Enter fullscreen mode Exit fullscreen mode

Case 1: No Error

      TRY → No Error → Skip CATCH → FINALLY runs
Enter fullscreen mode Exit fullscreen mode

Case 2: Error Occurs

     TRY → Error → CATCH runs → FINALLY runs
Enter fullscreen mode Exit fullscreen mode

Top comments (0)