0% found this document useful (0 votes)
20 views8 pages

Java Exception Handling Explained

The document discusses exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It categorizes exceptions into checked, unchecked, and errors, detailing their differences and providing examples of how to use try, catch, finally, throw, and throws keywords for effective exception management. Additionally, it illustrates various scenarios and code examples to demonstrate the functionality and necessity of exception handling in Java programming.

Uploaded by

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

Java Exception Handling Explained

The document discusses exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It categorizes exceptions into checked, unchecked, and errors, detailing their differences and providing examples of how to use try, catch, finally, throw, and throws keywords for effective exception management. Additionally, it illustrates various scenarios and code examples to demonstrate the functionality and necessity of exception handling in Java programming.

Uploaded by

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

UNIT-3

Exception Handling

The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.

What is exception?

In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception: The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions [Link], SQLException etc. Checked
exceptions are checked at compile-time.

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

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.
Hierarchy of Java Exception classes

Checked and UnChecked Exceptions


Uncaught Exception

The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs
and terminates the thread.

Example:
import [Link];
public class UncaughtExceptionExample
{
public static void main(String[] args)
{
Scanner read = new Scanner([Link]);
[Link]("Enter the a and b values: ");
int a = [Link]();
int b = [Link]();
int c = a / b;
[Link](a + "/" + b +" = " + c);
}
}

Output:
Java try block

Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try

block only. You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{


public static void main(String args[]){
int data=50/0;//may throw exception
[Link]("rest of the code...");
}}
Output:
Exception in thread main [Link]:/ by zero

As displayed in the above example, rest of the code is not executed (in such case,
rest of the code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception
will not be executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.


public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException
e){[Link](e);}
[Link]("rest of the code...");
}}
Output:
Exception in thread main
[Link]:/ by zero rest of the
code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use
java multi catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){[Link]("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");
9. }
10. catch(Exception e){[Link]("common task completed");
11. }
12. [Link]("rest of the code...");
13. } }

Output:task1
completed
rest of the
code...

Java nested try example

Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[]){
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException
e){[Link](e);} [Link]("other
statement);
}catch(Exception
e){[Link]("handeled");}
[Link]("normal flow..");
}
1. }
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.

Usage of Java finally

Case 1

Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always
executed");} [Link]("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Java throw keyword

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.

The syntax of java throw keyword is given below.

1. throw exception;

Java throw keyword example

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

1. public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}}

Output:

Exception in thread main [Link]:not valid


Java throws keyword

The Java throws keyword is used to declare an exception. It gives an 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.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }
4.

Java throws example

Let's see the example of java throws clause which describes that checked
exceptions can be propagated by throws keyword.

import [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception

}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){[Link]("exception
handled");} }
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow..."); } }
Output:
exception handled
normal flow...

You might also like