Вы находитесь на странице: 1из 23

Exception Handling in Java

What is an exception?
An exception is an abnormal condition that changes the normal flow

of control in a program
An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's instructions

Types of Exception?
Types of Exception
1) Checked Exception
Checked exceptions are checked at compile-time. The classes that
extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException, SQLException etc.
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.
3) Error
Errors are not possible to handle in your program code

How can we handle exception?


Exception Handling is a mechanism to handle exceptions

such as ClassNotFound, IO, SQL, etc.


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

Exception Hierarchy

Exception Handling Keywords


There are 5 keywords used in java exception handling.
try
catch
finally
throw
throws

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
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}

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.

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 must be followed by try or catch
block.

Example of try-catch-finally
public class Test {
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

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.
Syntax of java throw keyword is given below.
throw exception;

Example of throw keyword


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...");
}
}

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
return_type method_name() throws exception_class_name{
//method code
}

Exception propagation using throws keyword


import java.io.IOException;
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){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

throws keyword(contd.)
Case1: You handle the exception

In case you handle the exception, the code will be executed fine whether exception occurs during the
program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
} }

throws keyword(contd.)
You declare the exception

A)In case you declare the exception, if exception does not occur, the code will be executed fine.
B)In case you declare the exception if exception occures, an exception will be thrown at runtime because
throws does not handle the exception.
Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
} }

throws keyword(contd.)
Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}

Difference between throw and throws


throws

throw
Java throw keyword is used to

Java throws keyword is used to

Checked exception cannot be

Checked exception can be

Throw is followed by an instance.

Throws is followed by class.

Throw is used within the method.

Throws is used with the method

explicitly throw an exception.


propagated using throw only.

You cannot throw multiple

exceptions.

declare an exception.

propagated with throws.

signature.

You can declare multiple exceptions

e.g.
public void method()throws
IOException,SQLException.

Exception handling with method overriding


There are many rules if we talk about methodoverriding with exception handling. The Rules
are as
follows:
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class Child extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
p.msg();
} }

Exception handling with method


overriding(Contd.)
If the superclass method declares an exception

If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}
}

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.
Example of java custom exception.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}

Custom Exception (contd.)


class TestCustomException1{
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...");
}
}

Thank You

Вам также может понравиться

  • Notes Java
    Notes Java
    Документ38 страниц
    Notes Java
    Rahul Manocha
    Оценок пока нет
  • Exception Handling in Java
    Exception Handling in Java
    Документ7 страниц
    Exception Handling in Java
    farhanasathath
    Оценок пока нет
  • Exception in Java
    Exception in Java
    Документ27 страниц
    Exception in Java
    Pratigya Gupta
    100% (1)
  • Java Problems with Solutions
    Java Problems with Solutions
    От Everand
    Java Problems with Solutions
    Рейтинг: 4.5 из 5 звезд
    4.5/5 (18)
  • Exceptions in Java
    Exceptions in Java
    Документ18 страниц
    Exceptions in Java
    Suhail.01
    0% (1)
  • Exception Handling in Java
    Exception Handling in Java
    Документ19 страниц
    Exception Handling in Java
    Duaa Hussein
    Оценок пока нет
  • Java Unit 3 Notes
    Java Unit 3 Notes
    Документ21 страница
    Java Unit 3 Notes
    binggivaway
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ16 страниц
    Exception Handling
    Khan.ali
    Оценок пока нет
  • Unit 3
    Unit 3
    Документ93 страницы
    Unit 3
    Mr.Benjmin Jashva Munigeti
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ6 страниц
    Exception Handling
    honaday945
    Оценок пока нет
  • Exception Handling in Java: The Runtime Errors So That Normal Flow of The Application Can Be Maintained
    Exception Handling in Java: The Runtime Errors So That Normal Flow of The Application Can Be Maintained
    Документ26 страниц
    Exception Handling in Java: The Runtime Errors So That Normal Flow of The Application Can Be Maintained
    vikram das
    Оценок пока нет
  • Exception Handling: Hierarchy of Java Exception Classes
    Exception Handling: Hierarchy of Java Exception Classes
    Документ7 страниц
    Exception Handling: Hierarchy of Java Exception Classes
    binduann
    Оценок пока нет
  • Java Unit 3
    Java Unit 3
    Документ11 страниц
    Java Unit 3
    Siva Nallabothula
    Оценок пока нет
  • Exception in Java
    Exception in Java
    Документ7 страниц
    Exception in Java
    yuvikatuteja4
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ18 страниц
    Exception Handling
    aditya
    Оценок пока нет
  • 31 Aug 2020 - Lecture12 Exceptionhandling
    31 Aug 2020 - Lecture12 Exceptionhandling
    Документ31 страница
    31 Aug 2020 - Lecture12 Exceptionhandling
    srishti
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ24 страницы
    Exception Handling
    sabarigirish s
    Оценок пока нет
  • Exception Handling in Java
    Exception Handling in Java
    Документ18 страниц
    Exception Handling in Java
    Siva Sankar
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ18 страниц
    Exception Handling
    RISHABH YADAV
    Оценок пока нет
  • uUNIT-III OOPC JAVA
    uUNIT-III OOPC JAVA
    Документ24 страницы
    uUNIT-III OOPC JAVA
    amancha SANJANA
    Оценок пока нет
  • CD Manual
    CD Manual
    Документ72 страницы
    CD Manual
    Siri Devoju
    Оценок пока нет
  • Java Unit-3
    Java Unit-3
    Документ13 страниц
    Java Unit-3
    Simran fatima
    Оценок пока нет
  • Exception Handling in Java
    Exception Handling in Java
    Документ19 страниц
    Exception Handling in Java
    pc03198007
    Оценок пока нет
  • PR - 9 - Exception Handling
    PR - 9 - Exception Handling
    Документ4 страницы
    PR - 9 - Exception Handling
    Rohan Rahalkar
    Оценок пока нет
  • Iot Oops Chap 3
    Iot Oops Chap 3
    Документ38 страниц
    Iot Oops Chap 3
    saniyainayath
    Оценок пока нет
  • CS405PC JP Unit-3
    CS405PC JP Unit-3
    Документ44 страницы
    CS405PC JP Unit-3
    MEGHANA 3
    Оценок пока нет
  • Java Exception Handling
    Java Exception Handling
    Документ14 страниц
    Java Exception Handling
    Dr Narayana Swamy Ramaiah
    Оценок пока нет
  • Unit V Exception - Handling
    Unit V Exception - Handling
    Документ26 страниц
    Unit V Exception - Handling
    Pinjari Soyab Shakil
    Оценок пока нет
  • Java Exception
    Java Exception
    Документ19 страниц
    Java Exception
    rajuvathari
    Оценок пока нет
  • Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
    Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
    Документ43 страницы
    Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
    mahalakshmi
    Оценок пока нет
  • Module 3
    Module 3
    Документ50 страниц
    Module 3
    Anish Shrestha
    Оценок пока нет
  • Exception Handling Exception Handling Keywords User Defined Exceptions Assertions
    Exception Handling Exception Handling Keywords User Defined Exceptions Assertions
    Документ19 страниц
    Exception Handling Exception Handling Keywords User Defined Exceptions Assertions
    Deepak Kumar
    Оценок пока нет
  • Java Unit 3
    Java Unit 3
    Документ34 страницы
    Java Unit 3
    Rakesh
    Оценок пока нет
  • Java Unit3
    Java Unit3
    Документ45 страниц
    Java Unit3
    beeram94
    Оценок пока нет
  • 23-Exception Handling in Java PDF
    23-Exception Handling in Java PDF
    Документ20 страниц
    23-Exception Handling in Java PDF
    pratigya g
    Оценок пока нет
  • Java Unit - III
    Java Unit - III
    Документ19 страниц
    Java Unit - III
    4018 MD GUFRAN UDDIN
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ16 страниц
    Exception Handling
    Harsh Amin
    Оценок пока нет
  • Chapter 3
    Chapter 3
    Документ11 страниц
    Chapter 3
    Supriya Nevewani
    Оценок пока нет
  • Unit - 3 Exception Handling and IO
    Unit - 3 Exception Handling and IO
    Документ17 страниц
    Unit - 3 Exception Handling and IO
    dharanya
    Оценок пока нет
  • OOP Chapter 4
    OOP Chapter 4
    Документ17 страниц
    OOP Chapter 4
    Oz G
    Оценок пока нет
  • Exception Handling in Java
    Exception Handling in Java
    Документ25 страниц
    Exception Handling in Java
    vinay.niranjan006
    Оценок пока нет
  • Java Unit-3
    Java Unit-3
    Документ61 страница
    Java Unit-3
    syeda husna
    Оценок пока нет
  • Java Exception Handling Notes
    Java Exception Handling Notes
    Документ31 страница
    Java Exception Handling Notes
    BSK
    Оценок пока нет
  • CS8392 - Oops - Unit Iii
    CS8392 - Oops - Unit Iii
    Документ43 страницы
    CS8392 - Oops - Unit Iii
    Mangaiyarkarasi Duraisamy
    Оценок пока нет
  • Pertemuan 11 - Exception Handling
    Pertemuan 11 - Exception Handling
    Документ34 страницы
    Pertemuan 11 - Exception Handling
    NIRVANA REYHAN YOGATAMA
    Оценок пока нет
  • Unit - III
    Unit - III
    Документ38 страниц
    Unit - III
    P.INDUMATHY Asst.Prof-CSE Dept
    Оценок пока нет
  • Java Exception
    Java Exception
    Документ15 страниц
    Java Exception
    Dr Narayana Swamy Ramaiah
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ105 страниц
    Exception Handling
    TechVeerendra's Software Solutions
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ13 страниц
    Exception Handling
    Jitendra Kumar Sahoo
    Оценок пока нет
  • Lecture 19-20 (Exceptions in Java)
    Lecture 19-20 (Exceptions in Java)
    Документ58 страниц
    Lecture 19-20 (Exceptions in Java)
    Jeeva Senthil Murugan
    Оценок пока нет
  • 08 Exceptions
    08 Exceptions
    Документ6 страниц
    08 Exceptions
    Marco Vraja
    Оценок пока нет
  • Java Exception
    Java Exception
    Документ30 страниц
    Java Exception
    Samarth Mangave
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ38 страниц
    Exception Handling
    Amal Ahmad
    Оценок пока нет
  • 4th Unit Complete Notes
    4th Unit Complete Notes
    Документ43 страницы
    4th Unit Complete Notes
    rajuvathari
    Оценок пока нет
  • Module 3
    Module 3
    Документ10 страниц
    Module 3
    Sony Sonu
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ11 страниц
    Exception Handling
    Sowjanya Balaga
    Оценок пока нет
  • Chapter 8
    Chapter 8
    Документ70 страниц
    Chapter 8
    Chris Suryadi Salim
    Оценок пока нет
  • Exception Handling
    Exception Handling
    Документ57 страниц
    Exception Handling
    Sonali Ekatpure
    Оценок пока нет
  • UNIT 3 - OOPS - Notes
    UNIT 3 - OOPS - Notes
    Документ38 страниц
    UNIT 3 - OOPS - Notes
    Ms.Thenmozhi IT Department
    Оценок пока нет
  • BE EXPERT IN JAVA Part- 2: Learn Java programming and become expert
    BE EXPERT IN JAVA Part- 2: Learn Java programming and become expert
    От Everand
    BE EXPERT IN JAVA Part- 2: Learn Java programming and become expert
    Оценок пока нет
  • Final Project Report
    Final Project Report
    Документ87 страниц
    Final Project Report
    Suhail.01
    Оценок пока нет
  • Presentation On Exceptions in Java
    Presentation On Exceptions in Java
    Документ23 страницы
    Presentation On Exceptions in Java
    Suhail.01
    Оценок пока нет
  • ENCh 02
    ENCh 02
    Документ33 страницы
    ENCh 02
    Nithin Joji Sankoorikkal
    Оценок пока нет
  • ENCh 02
    ENCh 02
    Документ33 страницы
    ENCh 02
    Nithin Joji Sankoorikkal
    Оценок пока нет