Exception handling in java - try catch and finally block

Опубликовано: 11 Октябрь 2024
на канале: Techlearners By Neeraj Saxena
164
5

#techlearners #java #exceptionhandling

Exception
Unexpected situation or unexpected error during program is
called exception
ex-
if we try to divide a number by zero
or
we try to access an element in an array which does not exist
these errors can be classified as
1. Compile time errors
2. Run time errors

Exception Handling
way of handling unexpected errors in a program.

Some common examples of exceptions are
Divide by zero
Accessing array element beyond its range
Hard disk crash
Try to access a file which does not exist

Exceptions can be handled by
try catch and finally blocks

in try block we put the code in which we expect error

in catch block we put the code for exception handling

in finally block we put the code which will be execute even
when the exception occurs.

Rules for try catch and finally blocks

1. for each try block there can be zero or more catch blocks.
2. catch or finally block must be used with try block.
3. try block must be followed by either atleast one catch.
or one finally block.
4. order of exception handling must be from most specific.

throws keyword
throws keyword is used to delegate the responsibility
of exception handling to the caller (It may be a method
or JVM) then caller method is responsible to handle that
exception.

Note
1. throws keyword is required only for checked exception
and usage of throws keyword for unchecked exception is
meaningless.
2. throws keyword is required only to convince compiler
and usage of throws keyword does not prevent abnormal
termination of program.
3. By the help of throws keyword we can provide information
to the caller of the method about the exception.

throw keyword

The throw keyword in Java is used to explicitly throw an
exception from a method or any block of code.
Used to throw an exception for a method.
Cannot throw multiple exceptions

classification of exceptions
There are mainly two types of exceptions:
checked and unchecked.
an error is considered as the unchecked exception.

1) Checked Exception
The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
e.g. IOException, SQLException etc.
Checked exceptions
are checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time,
but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.