What is an Exception? Explain by giving an example

What is an Exception? Explain by giving an example.

Exceptions are errors that occur at runtime and disrupt the normal flow of execution of instructions in a program.

An exception object is created by the method in which an error occurs which is then handed over to the runtime system. This process is called throwing an exception. The object contains the details of the error, its type, etc.

An exception handler is the code that executes after an exception is encountered. The runtime method searches the call stack to find an appropriate method containing the code for handling the exception. The runtime system after receiving the exception tries to find a suitable way to handle it.

When the type of exception thrown matches the type of exception that can be handled, the exception is passed on to the handler so as to catch the exception. The three types of exceptions are:

checked exceptions, errors and runtime exceptions.

An event that occurs during the execution of a program that disrupts the normal flow of instructions is called an exception.

Example:
public static void Main ()
{
   int numerator, denominator;
   try
   {
       int quotient = numerator/denominator;
   }
       catch (DivideByZeroException e)
       {
           System.out.println("Divide By Zero Exception Occurred!");
       }
}
Checked Exceptions vs. Unchecked Exceptions
Checked Exceptions vs. Unchecked Exceptions - A checked exception is a subclass of Exception excluding class RuntimeException and its subclasses...
What is a user defined exception?
What is a user defined exception? - At times, depending on the need of a program, a programmer might need to create his own set of exceptions...
What are the different ways to generate an Exception?
Different ways to generate an Exception - There are 3 ways in which the exceptions are generated:...
Post your comment