What
is an exception?
An Exception can be anything which
interrupts the normal flow of the program. When an Exception occurs the normal
flow of the program is disrupted and the program/Application terminates
abnormally, which needs to be handled.
When
an exception can occur?
Exception can occur at runtime
(known as runtime exceptions) as well as at compile-time (known Compile-time
exceptions).
Reasons
for Exceptions
There can be several reasons for an
exception. For example, following situations can cause an exception – Opening a
non-existing file, Network connection problem, Operands being manipulated are
out of prescribed ranges, class file missing which was supposed to be loaded
and so on.
Difference
between error and exception
Errors : These are not exceptions at
all, but problems that arise beyond the control of the user or the programmer.
Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Exceptions are conditions within the
code. A developer can handle such conditions and take necessary corrective
actions. Few examples –
• DivideByZero
exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
Why
to handle exception?
If an exception is raised, which has
not been handled by programmer then program execution can get terminated and
system prints a non user friendly error message.
Types
of exceptions
There are two types of exceptions
1)Checked exceptions
2)Unchecked exceptions
Checked
exceptions
A checked exception is an exception
that occurs at the compile time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored at the time of
compilation, the Programmer should take care of (handle) these exceptions.
For example, if you use FileReader
class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then anFileNotFoundException occurs, and compiler
prompts the programmer to handle the exception.
Examples
of Checked Exceptions :-
ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.
Unchecked
Exceptions
An Unchecked exception is an
exception that occurs at the time of execution, these are also called as
Runtime Exceptions, these include programming bugs, such as logic errors or
improper use of an API. runtime exceptions are ignored at the time of
compilation.
For example, if you have declared an
array of size 5 in your program, and trying to call the 6th element of the
array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Examples
of Unchecked Exceptions:-
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.