KEMBAR78
Exception Handling | PDF | Java (Programming Language) | Computer Programming
0% found this document useful (0 votes)
30 views8 pages

Exception Handling

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the types of exceptions (checked, unchecked, and errors), the use of try-catch blocks, and the functionality of finally and throw keywords. Additionally, it covers the concept of custom exceptions and provides examples to illustrate the principles discussed.

Uploaded by

prabhatyadavcs
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)
30 views8 pages

Exception Handling

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the types of exceptions (checked, unchecked, and errors), the use of try-catch blocks, and the functionality of finally and throw keywords. Additionally, it covers the concept of custom exceptions and provides examples to illustrate the principles discussed.

Uploaded by

prabhatyadavcs
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
You are on page 1/ 8

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY

DEPARTMENT OF EEE

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 bemaintained.

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. CheckedException
2. UncheckedException
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 e.g.IOException, SQLException etc. Checked exceptions are checked
atcompile-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 checkedatruntime.

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

JAVA PROGRAMMING Page 1


Hierarchy of Java Exception classes

Checked and UnChecked Exceptions

JAVA PROGRAMMING Page 2


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 throwexception
3. }catch(Exception_class_Name

ref){}Syntax of try-finallyblock

1. try{
2. //code that may throwexception
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
System.out.println("rest of
thecode...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:/ byzero

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{


JAVA PROGRAMMING Page 3
JAVA PROGRAMMING Page 4
public static void main(String args[]){
try{
intdata=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exception in thread main java.lang.ArithmeticException:/ 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 classTestMultipleCatchBlock{
2. public static void main(Stringargs[]){
3. try{
4. inta[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 iscompleted");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
9. }
10. catch(Exception e){System.out.println("common taskcompleted");
11. }
12. System.out.println("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.

classExcep6{
public static void main(String args[]){
try{t
ry{
System.out.println("going to divide");
intb =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{

JAVA PROGRAMMING Page 5


inta[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("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.

classTestFinallyBlock{
public static void main(String args[]){
try{ intdata=25/
5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("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. throwexception;

JAVA PROGRAMMING Page 6


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
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}}

Output:

Exception in thread main java.lang.ArithmeticException:notvalid


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() throwsexception_class_name{
2. //method
code3. }
4.

Java throws example

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

importjava.io.IOException;
classTestthrows1{ voidm()thro
ws IOException{
throw new IOException("device error");//checked exception

JAVA PROGRAMMING Page 7


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

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.

Let's see a simple example of java custom exception.

classInvalidAgeException extends
Exception{ InvalidAgeException(String s){
super(s);
}}
classTestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{ validate(13
);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}}

Output:Exception occured: InvalidAgeException:not valid rest of the code...

JAVA PROGRAMMING Page 8

You might also like