0% found this document useful (0 votes)
267 views7 pages

Exception Handling in Java

Exception handling in Java allows the normal flow of a program to continue despite runtime errors. There are two types of exceptions: checked exceptions which are verified at compile-time and unchecked exceptions which are verified at runtime. The try-catch block is used to handle exceptions where code in the try block may throw exceptions, and catch blocks handle specific exceptions. Finally blocks contain cleanup code such as closing streams.

Uploaded by

Gagan Bansal
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
267 views7 pages

Exception Handling in Java

Exception handling in Java allows the normal flow of a program to continue despite runtime errors. There are two types of exceptions: checked exceptions which are verified at compile-time and unchecked exceptions which are verified at runtime. The try-catch block is used to handle exceptions where code in the try block may throw exceptions, and catch blocks handle specific exceptions. Finally blocks contain cleanup code such as closing streams.

Uploaded by

Gagan Bansal
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 7

Exception Handling in Java

The Exception Handling in Java is one of the powerful mechanisms to handle the
runtime errors such as IOException, ClassNotFoundException, SQLException,
RemoteException, etc. so that normal flow of the application can be maintained.
Exception is an abnormal condition. In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is thrown at runtime. The advantage
of exception handling is to maintain the normal flow of the application.

Suppose there are 10 statements in program and there occurs an exception at statement
5, the rest of the code will not be executed. If we perform exception handling, the rest of
the statement will be executed. That is why we use exception handling in Java.

1. Types of Java Exceptions:- There are two types of exceptions: checked and
unchecked. Here, an error is considered as the unchecked exception. According
to Oracle, there are three types of exceptions:

a) 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.

b) 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.

c) Error:- Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.

2. Java Exception Keywords:-There are 5 keywords in handling exceptions in Java.

Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an
exception. It specifies that there may occur an exception in the method.
3. Hierarchy of Java Exception classes:- The java.lang.Throwable class is the root
class of Java Exception hierarchy which is inherited by two subclasses: Exception
and Error. A hierarchy of Java Exception classes are given below:
4. Common Scenarios of Java Exceptions:- There are given some scenarios where
unchecked exceptions may occur. They are as follows:

a) A scenario where ArithmeticException occurs:- If we divide any number by zero,


there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
b) A scenario where NullPointerException occurs:- If we have a null value in any
variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
c) A scenario where NumberFormatException occurs:- The wrong formatting of
any value may occur NumberFormatException. Suppose I have a string variable
that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
d) A scenario where ArrayIndexOutOfBoundsException occurs:- If you are
inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

5. Java try-catch block

1) Java try block

Java try block is used to enclose the code that might throw an exception. It must be used
within the method. If an exception occurs at the particular statement of try block, the
rest of the block code will not execute. So, it is recommended not to keeping the code in
try block that will not throw an exception. Java try block must be followed by either
catch or finally block.
1. try{
2. //code that may throw an exception

3. }catch(Exception_class_Name ref){}

2 Java catch block

Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception. The catch block must be used after the try block only.
You can use multiple catch block with a single try block.
3 Internal working of java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.

6. Java catch multiple exceptions

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, for different tasks at the occurrence of different
exceptions, use java multi-catch block.
At a time only one exception occurs and at a time only one catch block is executed. And
all catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
7. Java Nested try block:- The try block within a try block is known as nested try
block in java. Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.

8. Java finally block:- Java finally block is a block that is used to execute important
code such as closing connection, stream etc. Java finally block is always executed
whether exception is handled or not. Java finally block follows try or catch block.
Finally block in java can be used to put "cleanup" code such as closing a file,
closing connection etc. For each try block there can be zero or more catch blocks,
but only one finally block. The finally block will not be executed if program
exits(either by calling System.exit() or by causing a fatal error that causes the
process to abort).
Note: If you don't handle exception, before terminating the program, JVM
executes finally block(if any).

9 Java throw exception:-The Java throw keyword is used to explicitly throw an


exception. We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception. We will
see custom exceptions later.

10 Java throws keyword:- The Java throws keyword is used to declare an


exception. It gives information to the programmer that there may occur an
exception so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained. Exception Handling is mainly used
to handle the checked exceptions. If there occurs any unchecked exception such
as NullPointerException, it is programmers fault that he is not performing check
up before the code being used.

Which exception should be declared


Ans) checked exception only, because:
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if there
occurs VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.

11 Difference between throw and throws in Java

No. throw throws


1) Java throw keyword is used to Java throws keyword is used to declare an
explicitly throw an exception. exception.
2) Checked exception cannot be Checked exception can be propagated
propagated using throw only. with throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.

12 Difference between final, finally and finalize

No. final finally finalize


1) Final is used to apply restrictions Finally is used to Finalize is used to
on class, method and variable. place important code, perform clean up
Final class can't be inherited, final it will be executed processing just
method can't be overridden and whether exception is before object is
final variable value can't be handled or not. garbage collected.
changed.
2) Final is a keyword. Finally is a block. Finalize is a method.

13 Java Custom Exception:- If you are creating your own Exception that is known
as custom exception or user-defined exception. Java custom exceptions are used
to customize the exception according to user need. By the help of custom
exception, you can have your own exception and message.
14 Assertion:- Assertion is a statement in java. It can be used to test your
assumptions about the program. While executing assertion, it is believed to be
true. If it fails, JVM will throw an error named AssertionError. It is mainly used
for testing purpose.

Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
Syntax of using Assertion:
There are two ways to use assertion.
1. assert expression;

2. assert expression1 : expression2;


Where not to use Assertion:
There are some situations where assertion should be avoid to use. They are:
1. According to Sun Specification, assertion should not be used to check
arguments in the public methods because it should result in appropriate
runtime exception e.g. IllegalArgumentException, NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.

You might also like