Sie sind auf Seite 1von 22

Exception Handling

Agenda

What is Exception?

 Why should we handle?

 Exception Class Hierarchy

 Types Of Exceptions

 Custom Exception
Exception

Exception is an abnormal condition in a scenario.

Reasons for Exceptions

➢A user has entered invalid data.

➢A file that needs to be opened cannot


be found.

➢A network connection has been lost in


the middle of communications or the
JVM has run out of memory
Why Should We Handle Exceptions

Advantages of Exception Handling

Stopping abnormal termination.


Separating error-Handling code from regular
business logic code.

 Propagating errors up to alert the caller.


 Grouping and differentiating error types.
Exception Types

Mainly there are 2 Types of Exceptions. They are :

 Checked Exceptions.

 Unchecked Exceptions
Unchecked Exceptions

 The classes that extend RuntimeException are known as


unchecked exceptions.

Unchecked exceptions are not checked at compile-time rather


they are checked at runtime.

E.g. ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException etc.
Checked Exceptions

The classes that extends Throwable class except


RuntimeException and Error
are known as checked exceptions.

These exceptions are raised when a program is working with the


external
requirement like accessing the file, accessing database tables,
assesing
remote machines etc.

Checked exceptions are checked at compile-time.

e.g.IOException, SQLException, ClassNotFoundException etc.


Exception Class Hierarchy
Error

Error is irrecoverable occurrence in a


program. We cannot handle Errors in a
Program

e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.
Exception Handling Keywords

Exception Handling is done by using 5 keywords of


java.

 try

 catch

 finally

 throw

 throws
Try Block

try block : try block is the place where we need to


store the code which is having a chance to raise an
Exception

Syntax :
try {
Code having the possibility to raise
exception.
}
Catch block

catch block : Catch block is used to handle the


Exception.

Syntax :

catch(Exception e) // Exception is class and e is Exception


Object
{
Print statements;
}
Example

Example on combination of both try and catch :

try {
int number/0; // Code having the possibility
to raise exception.
}

catch(Exception e)
{
System.out.println("Divider number should
not be Zero");
}

Output :

Divider number should not be Zero.


Finally Block

finally block : The finally block is a block that is always


executed irrespective of the Exception raised.

Syntax :

finally
{
Exception handling statements;
}
Example

Example on finally block :

class SimpleExample{
public static void main(String args[]) {

try{
int data=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...
Throw

throw :The throw keyword is used to explictily throw an


exception.throw key word is mainly used to inform the JVM
where an Exception is going to be rasied.

Syntax :

if(age<18)

{
throw new ArithmeticException("not valid");
}
Example

Example on throw keyword

class ExceptionDemo{

static void validateAge(int age){


if(age<18)
throw new ArithmeticException("Not Valid Age to Vote");
else
System.out.println("Valid Age to Age");
}

public static void main(String args[]){


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

Output: Exception in thread main


java.lang.ArithmeticException:not valid
Throws

throws : The throws keyword is used to declare an


exception. Handling the Esxception to calling method or
calling class

Syntax :

void method_name() throws exception_class_name


{
...
}
Example

Example on throws Keyword :


class ThrowsDemo{

void xyz()throws IOException{


throw new IOException("device error");//checked exception
}
void abc()throws IOException{
xyz();
}
void pqr(){
try{
abc();
}catch(Exception e){System.out.println("exception handled");}
}

public static void main(String args[]){


Simple obj=new Simple();
obj.pqr();
System.out.println("normal flow...");
}
}

Output:exception handled
Custom Exception

Creating our own Exception Class is called as Custom


Exception.

Our defined class should extend Exception class to create


Custom Exception Class.

Syntax :

Class InvalidAgeException extends Exception


{
....
}
Custom Exception Continue

Example on creating Custom Exception :

Class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}
Here we have created an Exception class named
InvalidAgeException by extending Exception class.

Here super keyword plays a crucial role. Super keyword is


used to store custom Exception message in Super class i.e
Exception Class. So at the time of using the custom exception
class we can get that message from the super class
Example
Now we use that InvalidAgeException class in our Program.

class ExceptionDemo{
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...

Das könnte Ihnen auch gefallen