0% found this document useful (0 votes)
14 views12 pages

Understanding Java Exception Handling

An exception is an interruption in the normal flow of a program, which can be handled using try-catch blocks. There are two types of exceptions: checked exceptions, which are checked at compile-time, and unchecked exceptions, which are checked at runtime. Exception handling allows developers to manage errors gracefully and maintain program control, with the finally block ensuring certain code executes regardless of exceptions.

Uploaded by

penchala swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views12 pages

Understanding Java Exception Handling

An exception is an interruption in the normal flow of a program, which can be handled using try-catch blocks. There are two types of exceptions: checked exceptions, which are checked at compile-time, and unchecked exceptions, which are checked at runtime. Exception handling allows developers to manage errors gracefully and maintain program control, with the finally block ensuring certain code executes regardless of exceptions.

Uploaded by

penchala swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exceptions

What is an exception?

An Exception can be anything which interrupts the normal flow of the program. When an
exception occurs program processing gets terminated and doesn’t continue further. In such cases
we get a system generated error message. The good thing about exceptions is that they can be
handled. We will cover the handling part later in this same tutorial.

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 indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal circumstances
by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –

 DivideByZero exception
 NullPointerException
 ArithmeticException
 ArrayIndexOutOfBoundsException

Advantages of Exception Handling

 Exception handling allows us to control the normal flow of the program by using exception
handling in program.
 It throws an exception whenever a calling method encounters an error providing that the calling
method takes care of that error.
 It also gives us the scope of organizing and differentiating between different error types using a
separate block of codes. This is done with the help of try-catch blocks.

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

Below is a brief about each however if you want a detailed tutorial with examples then you can
refer Checked and Unchecked exceptions in Java.

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, it will give compilation error.

Examples of Checked Exceptions :-


ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check
whether the programmer has handled them or not but it’s the duty of the programmer to handle
these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not
check to see if a method handles or throws these exceptions.

Examples of Unchecked Exceptions:-


ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.

Exception hierarchy
We can handle exception by using try catch block.

try: try is used to define block of code where exception can occur.

The try block contains a block of program statements within which an exception might occur. A
try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must followed by a Catch block or Finally block or both.

Syntax of try block


try{
//statements that may cause an exception
}
catch: catch is used to match specific type of exception. There could be more than one catch
clause for one try block.

What is Catch Block?

A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic exception
occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

Syntax of try catch in java


try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}

Flow of try catch block

1. If an exception occurs in try block then the control of execution is passed to the catch block from
try block. The exception is caught up by the corresponding catch block. A single try block can
have multiple catch statements associated with it, but each catch block can be defined for only
one exception class. The program can also contain nested try-catch-finally blocks.
2. After the execution of all the try blocks, the code inside the finally block executes. It is not
mandatory to include a finally block at all, but if you do, it will run regardless of whether an
exception was thrown and handled by the try and catch blocks.

An example of Try catch in Java


3. class Example1 {
4. public static void main(String args[]) {
5. int num1, num2;
6. try {
7. // Try block to handle code that may cause exception
8. num1 = 0;
9. num2 = 62 / num1;
10. [Link]("Try block message");
11. } catch (ArithmeticException e) {
12. // This block is to catch divide-by-zero error
13. [Link]("Error: Don't divide a number by zero");
14. }
15. [Link]("I'm out of try-catch block in Java.");
16. }
17. }
18. Output:
19. Error: Don't divide a number by zero
20. I'm out of try-catch block in Java.

Multiple catch blocks in Java

1. A try block can have any number of catch blocks.


2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:

catch(Exception e){
//This catch block catches all the exceptions
}

Example of Multiple catch blocks


class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
[Link]("First print statement in try block");
}
catch(ArithmeticException e){
[Link]("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
[Link]("Warning: Some Other exception");
}
[Link]("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
3. If multiple catch blocks are present in a program then the above mentioned catch block should
be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and
the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.

finally: finally determine block of code which will always execute after try block. Even in case
of Exception.

What is Finally Block

1. A finally statement must be associated with a try statement. It identifies a block of statements
that needs to be executed regardless of whether or not an exception occurs within the try block.

2. After all other try-catch processing is complete, the code inside the finally block executes. It is
not mandatory to include a finally block at all, but if you do, it will run regardless of whether an
exception was thrown and handled by the try and catch parts of the block.

3. In normal execution the finally block is executed after try block. When any exception occurs
first the catch block is executed and then finally block is executed.

4. An exception in the finally block, exactly behaves like any other exception.

5. The code present in the finally block executes even if the try or catch block contains control
transfer statements like return, break or continue.

To understand above concepts better refer the below examples.

Syntax of Finally block


try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}

Cases when the finally block doesn’t execute

The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

Finally block and Return statement

Finally block executes even if there is a return statement in try-catch block.

Finally block and Return statement


Finally block executes even if there is a return statement in try-catch block. PFB the example –
class JavaFinally
{
public static void main(String args[])
{
[Link]([Link]());
}
public static int myMethod()
{
try {
return 112;
}
finally {
[Link]("This is Finally block");
[Link]("Finally block ran even after return statement");
}
}
}
Output of above program:
This is Finally block
Finally block ran even after return statement
112

Finally and Close()

Close() is generally used to close all the open streams in one go. Its a good practice to use close()
inside finally block. Since finally block executes even if exception occurs so you can be sure that
all input and output streams are closed properly regardless of whether the exception occurs or
not.

E.g.

....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
[Link](writableObject);
}
finally{
[Link]();
}
}
catch(IOException e1){
[Link](e1);
}
...

Finally block without catch

A try-finally block is possible without catch block. Which means a try block can be used with
finally without having a catch block.

try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
[Link](writableObject);
}
finally{
[Link]();
}
}
catch(IOException e1){
[Link](e1);
}

Finally block and [Link]()

[Link]() statement behaves differently than return statement. Unlike return statement
whenever [Link]() gets called in try block then Finally block doesn’t get executed. Refer
the below example to understand it better –

....
try {
//try block
[Link]("Inside try block");
[Link](0)
}
catch (Exception exp) {
[Link](exp);
}
finally {
[Link]("Java finally block");
}
....

In the above example if the [Link](0) gets called without any exception then finally won’t
execute. However if any exception occurs while calling [Link](0) then finally block will be
executed.

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.

S Methods with Description


N
1 public String getMessage()

Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
2 public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.


3 public String toString()

Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()

Prints the result of toString() along with the stack trace to [Link], the error output
stream.
5 public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method
at the bottom of the call stack.
6 public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught,
by using the throw keyword.

Try to understand the difference between throws and throw keywords, throws is
used to postpone the handling of a checked exception and throw is used to invoke an
exception explicitly.

Throw vs Throws in java


1. Throws clause in used to declare an exception and thow keyword is used to throw an exception
explicitly.
2. If we see syntax wise than throw is followed by an instance variable andthrows is followed by
exception class names.
3. The keyword throw is used inside method body to invoke an exception andthrows clause is used in
method declaration (signature).
for e.g.
Throw:
....
static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
[Link]("Error: "+[Link]());
}
}
....
Throws:
public void sample() throws ArithmeticException{
//Statements

.....

//if (Condition : There is an error)


ArithmeticException exp = new ArithmeticException();
throw exp;
...
}
4. By using Throw keyword in java you cannot throw more than one exception but using throws you can
declare multiple exceptions. PFB the examples.
for e.g.
Throw:
throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")
Throws:
throws IOException, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
That’s all I have for this topic. Let me know if I missed any difference between throw and throws in
Java. If you have any queries regarding it, please feel free to ask me. Just drop a comment below, I’ll try
to answer as soon as possible.

User-defined Exceptions:

You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:

 All exceptions must be a child of Throwable.


 If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{


}

You just need to extend the predefined Exception class to create your own Exception. These are
considered to be checked exceptions. The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it a checked exception. An exception
class is like any other class, containing useful fields and methods.

Cheat-sheet

 Checked & unchecked exception are two type of Exception.


 Checked exception are those exception which are subtype of Exception class but excluding
classes which extends Runtime exception.
 Subtype of Error and Runtime Exceptions comes under unchecked Exception.
 Finally block will always be invoked in all condition.
 [Link]() is the only way when finally block will not get executed coz in that case JVM will
shut down.
 Custom Exception can also be created by extending Exception class.
 Catch block should be order in the form of most specific to most general. Otherwise compiler
will complain for unreachable code.

You might also like