SlideShare a Scribd company logo
Exception Handling
in JAVA
By – Kunal Singh
Jaskaran Singh
CLASS PRESENTATION
What is Exception?
• An exception is a problem that arises during the
execution of a program. When an Exception occurs the
normal flow of the program is disrupted and the
program terminates abnormally
• Exception Handling is a mechanism to handle runtime
errors.
Situations in which exception
can occur :-
• User entering invalid data.
• Opening a non-existing file.
• Network connections problem.
• Number format exception.
Types of Exception
• Checked exceptions − A checked exception is an
exception that occurs at the compile time, these are also
called as Compile time exceptions.
• Unchecked exceptions − An unchecked exception is an
exception that occurs at the time of execution. These are
also called as Runtime Exceptions.
• Errors − These are not exceptions at all, but problems
that arise beyond the control of the user or the
programmer. e.g. OutOfMemoryError,
VirtualMachineError.
Exception Hierarchy
Try-Catch Block
• Try block- It is used to enclose
the code that might throw an
exception. It must be used within
the method.
• Catch block- It is used to handle
the Exception. It must be used
after the try block only. It involves
declaring the type of exception
you are trying to catch.
Syntax:-
try
{
// Protected code
}
catch(ExceptionName e)
{
// Catch block
}
Example (without exception handling)
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;
System.out.print("rest ");
System.out.print(“of");
System.out.print(“the");
System.out.print(“code");
}
}
Output- Exception in thread main
java.lang.ArithmeticException:/ by zero
Example (with exception handling)
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}
catch(ArithmeticException e)
{ System.out.println(e);
}
System.out.println("rest of the code...");
} }
Output- Exception in thread main
java.lang.ArithmeticException:/ by zero
rest of the code...
Multiple Catch Block
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println(“e");}
catch(ArrayIndexOutOfBoundsException e){System.out.println(“e");}
System.out.println("rest of the code..."); }
}
Output- Exception in thread main
java.lang.ArithmeticException:/ by zero
rest of the code...
Some common Sub-Classes of exception
are:-
• ArithmeticException - If we divide any number by
zero, there occurs an ArithmeticException
int a=50/0;
• NullPointerException - If we have null value in any
variable, performing any operation by the variable
occurs an NullPointerException.
String s=null;
System.out.println(s.length());
• ArrayIndexOutOfBoundsException - If we are
inserting any value in the wrong index, it would
result ArrayIndexOutOfBoundsException.
int a[]=new int[5];
a[10]=50;
• NumberFormatException- The wrong formatting
of any value, may occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);
Finally block
• Finally block is a block
that is used to execute
important code.
• It is always executed
whether exception is
handled or not.
• The finally block follows
a try block or a catch
block.
try {
// Protected code
}
catch (ExceptionType1 e1)
{ // Catch block
}
catch (ExceptionType2 e2)
{ // Catch block
}
catch (ExceptionType3 e3)
{ // Catch block
}
finally
{
// The finally block always
executes.
}
Example
public class TestFinallyBlock2{
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 will execute");}
} }
Output:Exception in thread main
java.lang.ArithmeticException:/ by zero
finally block will execute
User defined exception
• If you are creating your own Exception that is
known as custom exception or user-defined
exception.
• All exceptions must be a child of Throwable.
Throw keyword
• 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 user
defined exception.
Syntax:- throw exception;
Throws Keyword
• The 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.
• Syntax:-
return_type method_name() throws exception_class_name{
//method code }
Difference between throw and
throws in Java
Exception handling in JAVA

More Related Content

What's hot

Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Abstraction java
Abstraction javaAbstraction java
Abstraction java
MahinImran
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
Sonya Akter Rupa
 
Java annotations
Java annotationsJava annotations
Java annotations
FAROOK Samath
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
Spring Boot
Spring BootSpring Boot
Spring Boot
koppenolski
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
java Features
java Featuresjava Features
java Features
Jadavsejal
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Presentation1
Presentation1Presentation1
Presentation1
Anul Chaudhary
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
BG Java EE Course
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 

What's hot (20)

Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Abstraction java
Abstraction javaAbstraction java
Abstraction java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java exception
Java exception Java exception
Java exception
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
java Features
java Featuresjava Features
java Features
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Presentation1
Presentation1Presentation1
Presentation1
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 

Similar to Exception handling in JAVA

A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Java chapter 6
Java chapter 6Java chapter 6
Java chapter 6
Abdii Rashid
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
thenmozhip8
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
AsisKumarTripathy
 

Similar to Exception handling in JAVA (20)

A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Java chapter 6
Java chapter 6Java chapter 6
Java chapter 6
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
 
Exception
ExceptionException
Exception
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 

Recently uploaded

Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 

Recently uploaded (20)

Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 

Exception handling in JAVA

  • 1. Exception Handling in JAVA By – Kunal Singh Jaskaran Singh CLASS PRESENTATION
  • 2. What is Exception? • An exception is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program terminates abnormally • Exception Handling is a mechanism to handle runtime errors.
  • 3. Situations in which exception can occur :- • User entering invalid data. • Opening a non-existing file. • Network connections problem. • Number format exception.
  • 4. Types of Exception • Checked exceptions − A checked exception is an exception that occurs at the compile time, these are also called as Compile time exceptions. • Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. • Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. e.g. OutOfMemoryError, VirtualMachineError.
  • 6. Try-Catch Block • Try block- It is used to enclose the code that might throw an exception. It must be used within the method. • Catch block- It is used to handle the Exception. It must be used after the try block only. It involves declaring the type of exception you are trying to catch. Syntax:- try { // Protected code } catch(ExceptionName e) { // Catch block }
  • 7. Example (without exception handling) public class Testtrycatch1{ public static void main(String args[]){ int data=50/0; System.out.print("rest "); System.out.print(“of"); System.out.print(“the"); System.out.print(“code"); } } Output- Exception in thread main java.lang.ArithmeticException:/ by zero
  • 8. Example (with exception handling) public class Testtrycatch2{ public static void main(String args[]){ try{ int data=50/0; } catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code..."); } } Output- Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
  • 9. Multiple Catch Block public class TestMultipleCatchBlock{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){System.out.println(“e");} catch(ArrayIndexOutOfBoundsException e){System.out.println(“e");} System.out.println("rest of the code..."); } } Output- Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
  • 10. Some common Sub-Classes of exception are:- • ArithmeticException - If we divide any number by zero, there occurs an ArithmeticException int a=50/0; • NullPointerException - If we have null value in any variable, performing any operation by the variable occurs an NullPointerException. String s=null; System.out.println(s.length());
  • 11. • ArrayIndexOutOfBoundsException - If we are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException. int a[]=new int[5]; a[10]=50; • NumberFormatException- The wrong formatting of any value, may occur NumberFormatException. String s="abc"; int i=Integer.parseInt(s);
  • 12. Finally block • Finally block is a block that is used to execute important code. • It is always executed whether exception is handled or not. • The finally block follows a try block or a catch block. try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } finally { // The finally block always executes. }
  • 13. Example public class TestFinallyBlock2{ 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 will execute");} } } Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block will execute
  • 14. User defined exception • If you are creating your own Exception that is known as custom exception or user-defined exception. • All exceptions must be a child of Throwable.
  • 15. Throw keyword • 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 user defined exception. Syntax:- throw exception;
  • 16. Throws Keyword • The 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. • Syntax:- return_type method_name() throws exception_class_name{ //method code }
  • 17. Difference between throw and throws in Java

Editor's Notes

  1. So exception are nothing but some abnormal and typically an event or conditions that arise during the execution which may intrrupt the normal flow of program. and
  2. And many more…
  3. There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. Checked- These exceptions cannot be ignored at the time of compilation, the programmer should take care of (handle) these exceptions. Unchecked - These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
  4. All exception classes are subtypes of the java.lang.Exception class. The exception class and error are the subclasses of the Throwable class.
  5. try block must be followed by either catch or finally block. You can use multiple catch block with a single try.
  6. In this program we have divide a integer value 50 by 0 and below this there are print messages. When we will execute it a exception ArithmeticException divided by zero will occur and rest of the code will not execute.
  7. Now in this code using try catch block the exception can be handeled. The try clock will throw exception object to catch block and it will handle the exception. An the output will be
  8. A try block can be followed by multiple catch blocks. We can make multiple catch block . If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. In this program first exception will occur which is aaruthmatic exceotion. The output will be-
  9. Here are the some sub classes of exception
  10. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
  11. It means we have to extend the exception class class InvalidAgeException extends Exception{    InvalidAgeException(String s){     super(s);    }   }   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...");     }   }  
  12. import java.lang.Exception; class MyException extends Exception { MyException(String message) { super(message); } } class TestMyException { output- caught myexception number is too small public static void main(String[] args) final block { int x = 5, y = 1000; try { float z = x / y; if(z < 0.01) { throw new MyException("Number is too small"); } }  catch(MyException e) { System.out.println(“caught My Exception”); System.out.println(e.getMessage()); } finally { Number is too small } System.out.println(“final block"); }} }
  13. Only checked exception should be declared