SlideShare a Scribd company logo
Exception Handling
Syntax for exception class handling
Try catch finally block
Throw
Throws
User Defined Exceptions
Exception class hirearachy
What is Exception
• 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 exceptions
• Checked exceptions
• Unchecked exceptions
Checked exceptions
compiler checks them during compilation to see whether the
programmer has handled them or not. If these exceptions are not
handled, it will give compilation error Eg:ClassNotFoundException
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. Eg:ArithmeticException
Exception handling in java
Syntax for Exception Handling
Try
{ //code that may throw exception }
catch(Exception_class_Name ref)
{}
Try Block
• 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,
• A try block must followed by a Catch block or Finally block or both
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.
Flow of try catch block
• 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.
• 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
public static void main(String[] args)
{ System.out.println("enter you choice in 1 or 2");
int n; Scanner sc=new Scanner(System.in);
n=sc.nextInt(); //taking input
switch(n)
{ /* * Arithmetic exception */
case 1:{ try
{ int numarator=26,denominator=0;
int c=numarator/denominator;
System.out.println("eception raised");
}
catch(ArithmeticException e)
{ System.out.println("arithmetic exception");
}
}/*case*/break;
/** number format exception*/
case 2:{
try
{ int a=Integer.parseInt("X");
}//try
catch(NumberFormatException e)
{ System.out.println("Numberformat exception"); }
}/*case*/break;
}//switch
}//public
Try catch finally block• public static void main(String[] args)
{ System.out.println("enter you choice in 1:multiple catch blocksn 2:Example finally blockn3:try block
with finally block");
int n; Scanner sc=new Scanner(System.in); n=sc.nextInt(); //taking input at runtime
switch(n)
{ /* * Arithmetic exception */
case 1:
{
case 2:{ try
{ int numarator=10,denominator=0;
int c=numarator/denominator;
System.out.println("the value of c is"+c);
}
catch(NumberFormatException e2)
{ System.out.println("arithmetic exception cought"); }
finally
{System.out.println("finally block excute every time"); }
}/*case*/break;
case 3:{ try
{ int numarator=10,denominator=0;
int c=numarator/denominator;
System.out.println("the value of c is"+c);
}
finally {System.out.println("finally block excute every time"); }
}/*case*/break;
}//switch
}//public
Throw
• The Java throw keyword is used to explicitly throw an exception
• We can throw either checked or unchecked exception in java by throw
keyword.
• Program execution stops on encountering throw statement, and the
closest catch statement is checked for matching type of exception.
Syntax
• throw ThrowableInstance
Creating Instance of Throwable Class
• Using a parameter in catch block.
• Creating instance with new operator.
public class Throw_Statement
{ static void age(int a)
{/** throwing an exception creating with new operator */
if(a<26)
{ throw new ArithmeticException("less than age");
}
else
System.out.println("Correct age");
}//age()
public static void main(String[] args)
{ age(10); }//main
}//class
####output####
Exception in thread "main" java.lang.ArithmeticException: less than age
Using a parameter in catch block
public class Throw_Statement
{ static void age(int a)
{ /* * throwing an exception with catch */
if(a<26)
{ try
{
throw new ArithmeticException("less than age");
}
catch(ArithmeticException e)
{
System.out.println("number is less than specifyed ::::"+e);
}
}
else
System.out.println("Correct age");
}//age()
public static void main(String[] args)
{ age(10); }//main
}//class
####output####
number is less than specifyed ::::java.lang.ArithmeticException: less than age
Throws
• 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
Syntax
• Return_type Method_name() throws Exception_Class_Name
• Throws key word example
User Defined Exceptions
• User defined exceptions in java are also known as Custom exceptions.
import java.io.IOException;
class My_Exception_Class extends Exception
{ String output;
public My_Exception_Class(String s)
{ output="the result is ="+s; }
/*public String toString()
{ return(output); }*/
}
public class Throw_Statement
{ public static void main(String[] args)
{ try
{
throw new My_Exception_Class("demo User Defined Exception");
}
catch(My_Exception_Class e)
{ System.out.println(e.output); }
}//main
}//class
####output###
the result is =demo User Defined Exception
Ad

More Related Content

What's hot (20)

Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
priyankazope
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Md.Shohel Rana ( M.Sc in CSE Khulna University of Engineering & Technology (KUET))
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
exception handling
exception handlingexception handling
exception handling
Manav Dharman
 
Exception
ExceptionException
Exception
Марія Русин
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 

Viewers also liked (20)

Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
Arjun Sridhar U R
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
Christopher Akinlade
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
Mumbai Academisc
 
Savr
SavrSavr
Savr
Shahar Barsheshet
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
Arjun Sridhar U R
 
09events
09events09events
09events
Waheed Warraich
 
Core java online training
Core java online trainingCore java online training
Core java online training
Glory IT Technologies Pvt. Ltd.
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
yugandhar vadlamudi
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
Arjun Sridhar U R
 
02basics
02basics02basics
02basics
Waheed Warraich
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
Pokequesthero
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
yugandhar vadlamudi
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
Mumbai Academisc
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
Rasan Samarasinghe
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
Shahid Rasheed
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
Rasan Samarasinghe
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training
Arjun Sridhar U R
 
Java notes 1 - operators control-flow
Java notes   1 - operators control-flowJava notes   1 - operators control-flow
Java notes 1 - operators control-flow
Mohammed Sikander
 
java swing
java swingjava swing
java swing
Waheed Warraich
 
Ad

Similar to Exception handling in java (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
Ravindra Rathore
 
java.pptx
java.pptxjava.pptx
java.pptx
sujatha629799
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exceptionn
ExceptionnExceptionn
Exceptionn
baabtra.com - No. 1 supplier of quality freshers
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
People Strategists
 
Exception Handling
Exception HandlingException Handling
Exception Handling
PRN USM
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Young Alista
 
Exception
ExceptionException
Exception
James Wong
 
Exception
ExceptionException
Exception
Luis Goldster
 
Exception
ExceptionException
Exception
Harry Potter
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Ad

More from yugandhar vadlamudi (13)

Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android
yugandhar vadlamudi
 
JButton in Java Swing example
JButton in Java Swing example JButton in Java Swing example
JButton in Java Swing example
yugandhar vadlamudi
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Packaes & interfaces
Packaes & interfacesPackaes & interfaces
Packaes & interfaces
yugandhar vadlamudi
 
JMenu Creation in Java Swing
JMenu Creation in Java SwingJMenu Creation in Java Swing
JMenu Creation in Java Swing
yugandhar vadlamudi
 
Adding a action listener to button
Adding a action listener to buttonAdding a action listener to button
Adding a action listener to button
yugandhar vadlamudi
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
yugandhar vadlamudi
 
Operators in java
Operators in javaOperators in java
Operators in java
yugandhar vadlamudi
 
Inheritance
InheritanceInheritance
Inheritance
yugandhar vadlamudi
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
yugandhar vadlamudi
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
yugandhar vadlamudi
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 

Recently uploaded (20)

E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 

Exception handling in java

  • 1. Exception Handling Syntax for exception class handling Try catch finally block Throw Throws User Defined Exceptions Exception class hirearachy
  • 2. What is Exception • 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 exceptions • Checked exceptions • Unchecked exceptions Checked exceptions compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled, it will give compilation error Eg:ClassNotFoundException 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. Eg:ArithmeticException
  • 4. Syntax for Exception Handling Try { //code that may throw exception } catch(Exception_class_Name ref) {} Try Block • 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, • A try block must followed by a Catch block or Finally block or both 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.
  • 5. Flow of try catch block • 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. • 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
  • 6. public static void main(String[] args) { System.out.println("enter you choice in 1 or 2"); int n; Scanner sc=new Scanner(System.in); n=sc.nextInt(); //taking input switch(n) { /* * Arithmetic exception */ case 1:{ try { int numarator=26,denominator=0; int c=numarator/denominator; System.out.println("eception raised"); } catch(ArithmeticException e) { System.out.println("arithmetic exception"); } }/*case*/break; /** number format exception*/ case 2:{ try { int a=Integer.parseInt("X"); }//try catch(NumberFormatException e) { System.out.println("Numberformat exception"); } }/*case*/break; }//switch }//public
  • 7. Try catch finally block• public static void main(String[] args) { System.out.println("enter you choice in 1:multiple catch blocksn 2:Example finally blockn3:try block with finally block"); int n; Scanner sc=new Scanner(System.in); n=sc.nextInt(); //taking input at runtime switch(n) { /* * Arithmetic exception */ case 1: { case 2:{ try { int numarator=10,denominator=0; int c=numarator/denominator; System.out.println("the value of c is"+c); } catch(NumberFormatException e2) { System.out.println("arithmetic exception cought"); } finally {System.out.println("finally block excute every time"); } }/*case*/break; case 3:{ try { int numarator=10,denominator=0; int c=numarator/denominator; System.out.println("the value of c is"+c); } finally {System.out.println("finally block excute every time"); } }/*case*/break; }//switch }//public
  • 8. Throw • The Java throw keyword is used to explicitly throw an exception • We can throw either checked or unchecked exception in java by throw keyword. • Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax • throw ThrowableInstance Creating Instance of Throwable Class • Using a parameter in catch block. • Creating instance with new operator.
  • 9. public class Throw_Statement { static void age(int a) {/** throwing an exception creating with new operator */ if(a<26) { throw new ArithmeticException("less than age"); } else System.out.println("Correct age"); }//age() public static void main(String[] args) { age(10); }//main }//class ####output#### Exception in thread "main" java.lang.ArithmeticException: less than age
  • 10. Using a parameter in catch block public class Throw_Statement { static void age(int a) { /* * throwing an exception with catch */ if(a<26) { try { throw new ArithmeticException("less than age"); } catch(ArithmeticException e) { System.out.println("number is less than specifyed ::::"+e); } } else System.out.println("Correct age"); }//age() public static void main(String[] args) { age(10); }//main }//class ####output#### number is less than specifyed ::::java.lang.ArithmeticException: less than age
  • 11. Throws • 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 Syntax • Return_type Method_name() throws Exception_Class_Name • Throws key word example
  • 12. User Defined Exceptions • User defined exceptions in java are also known as Custom exceptions. import java.io.IOException; class My_Exception_Class extends Exception { String output; public My_Exception_Class(String s) { output="the result is ="+s; } /*public String toString() { return(output); }*/ } public class Throw_Statement { public static void main(String[] args) { try { throw new My_Exception_Class("demo User Defined Exception"); } catch(My_Exception_Class e) { System.out.println(e.output); } }//main }//class ####output### the result is =demo User Defined Exception
  翻译: