What is an Exception ?

9 Shares

Exception In Java

  • In procedural programming, it is the responsibility of the programmer to ensure that the programs are error-free in all aspects.
  • Errors have to be checked and handled manually by using some error codes.
  • But this kind of programming was very cumbersome and led to spaghetti code
  • Java provides an excellent mechanism for handling runtime errors.
  • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
  • The ability of a program to intercept run-time errors, take corrective measures and continue execution is referred to as exception handling.

There are various situations when an exception could occur:

  • Attempting to access a file that does not exist.
  • Inserting an element into an array at a position that is not within its bounds.
  • Performing some mathematical operation that is not permitted.
  • Declaring an array using negative values.

Uncaught Exceptions

class Demo {
public static void main(String
int x = 0;
int y = 50/x;
System.out.println(“y = “ +y);
}
}

Although this program will compile, when you execute it, the Java run-time-system will generate an exception and displays the following output on the console :

java.lang.ArithmeticException: / by zero

at Demo.main(Demo.java:4)

Exception Handling Techniques :

  • There are several built-in exception classes that are used to handle the very fundamental errors that may occur in your programs.
  • You can create your own exceptions also by extending the Exception class.
  • These are called user-defined exceptions and will be used in situations that are unique to your applications.

Handling Runtime Exceptions:

  • Whenever an exception occurs in a program, an object representing that exception is created and thrown in the method in which the exception occurred.
  • Either you can handle the exception, or ignore it.
  • In the latter case, the exception is handled by the Java run-time-system and the program terminates.
  • However, handling the exceptions will allow you to fix it, and prevent the program from terminating abnormally

 

9 Shares

Leave a Reply