You are on page 1of 2

an unexpected unwanted event that disturbs normal flow of the program

is called exception
tyrepunctured expection

An Exception is nothing but a runtime error. Whenever an error occurs at


runtime, immediately it will throw an exception and the program will be terminated
abnormally. Using this concept, we can handle the exceptions, so that we can
continue the program execution and avoid the abnormal program termination.

All the exceptions are pre-defined classes. All Exception types are sub
classes of the built-in class Throwable . Immediately below Throwable class, two
subclasses Exception and Error. Important subclass of Exception called
RuntimeException, from which all the exceptions have been derived. Error class,
which defines exceptions that are not to be caught by our programs.

Java exception handling is managed via five keywords. try, catch, throw, throws
and finally.

Built-in exceptions are categorized into two types.

1. Checked Exceptions : - These are invalid conditions that occur due to


invalid input, network connectivity problems or database problems. These exceptions
are the objects of the Exception class or any of its subclasses excluding
RuntimeException class.
Ex: ClassNotFoundException, IOException, IllegalAccessException,
InstantiationException, NoSuchMethodException

2. Unchecked Exceptions :- These are the runtime errors that occur because of
programming errors.
Ex: ArithmeticException, ArrayIndexOutOfBoundsException,
IllegalArgumentException, NullPointerException, NumberFormatException etc

try
{
-executable statements which may throw an exception
}

catch(Exception e)
{
- some message -
}

finally
{
--statements will be executed compulsorily --
}

You can have any number of try blocks in a program. we can use nested try
block also, i.e. try block inside a try block.

Inside the try block, once the exception is raised immediately the control will be
thrown out of the try block. It doesn't allow the control to go to the next
statement in try block.
So catch should be followed immediately after the try block, to catch the
exceptions. Finally also can be written after try block.

throw :- used to throw the required exception intentionally. By using throw in


catch block, again we can rethrow the exception to outer block.
throws :- used to specify the types of exceptions, the method can throw. If a
method is throwing an exception, which it is not handling, then it must
specify.

printing a stack trace :- We can find out the line or method, where the exception
is raised by using printStackTrace() method in catch block.
eg: catch(ArithmeticException e)
{
e.printStackTrace();
}

You might also like