SlideShare a Scribd company logo
5
Most read
7
Most read
9
Most read
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 (20)

PPTX
java interface and packages
VINOTH R
 
PPS
Java Exception handling
kamal kotecha
 
PPTX
Polymorphism presentation in java
Ahsan Raja
 
PPTX
Exception handling in Java
Ankit Rai
 
PPTX
Exception handling in java
ARAFAT ISLAM
 
PPTX
Method Overloading in Java
Sonya Akter Rupa
 
PPTX
Interface in java
PhD Research Scholar
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPTX
Java 8 Lambda and Streams
Venkata Naga Ravi
 
PPTX
Java packages
BHUVIJAYAVELU
 
PPTX
Method overloading
Lovely Professional University
 
PPTX
Virtual base class
Tech_MX
 
PPT
Basic concept of OOP's
Prof. Dr. K. Adisesha
 
PPSX
Strings in Java
Hitesh-Java
 
PPTX
Exception handling in java
Lovely Professional University
 
PDF
Collections In Java
Binoj T E
 
PPT
Exception handling
Tata Consultancy Services
 
PPT
Oop java
Minal Maniar
 
PPTX
Java Annotations
Serhii Kartashov
 
PPT
Method overloading
Azaz Maverick
 
java interface and packages
VINOTH R
 
Java Exception handling
kamal kotecha
 
Polymorphism presentation in java
Ahsan Raja
 
Exception handling in Java
Ankit Rai
 
Exception handling in java
ARAFAT ISLAM
 
Method Overloading in Java
Sonya Akter Rupa
 
Interface in java
PhD Research Scholar
 
9. Input Output in java
Nilesh Dalvi
 
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Java packages
BHUVIJAYAVELU
 
Method overloading
Lovely Professional University
 
Virtual base class
Tech_MX
 
Basic concept of OOP's
Prof. Dr. K. Adisesha
 
Strings in Java
Hitesh-Java
 
Exception handling in java
Lovely Professional University
 
Collections In Java
Binoj T E
 
Exception handling
Tata Consultancy Services
 
Oop java
Minal Maniar
 
Java Annotations
Serhii Kartashov
 
Method overloading
Azaz Maverick
 

Similar to Exception handling in JAVA (20)

PPT
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
PPTX
Exception Handling.pptx
primevideos176
 
PPTX
Exceptions handling in java
junnubabu
 
PPTX
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
PPTX
Exception handling in java.pptx
Nagaraju Pamarthi
 
PPTX
Interface andexceptions
saman Iftikhar
 
PPTX
L14 exception handling
teach4uin
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPTX
Exception handling in java-PPT.pptx
sonalipatil225940
 
PPT
Exceptions
Soham Sengupta
 
PPTX
java exception.pptx
SukhpreetSingh519414
 
PPT
8.Exception handling latest(MB).ppt .
happycocoman
 
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
PDF
Java unit 11
Shipra Swati
 
DOCX
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
PPTX
Exception handling in java
Elizabeth alexander
 
PPTX
Chap2 exception handling
raksharao
 
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exception Handling.pptx
primevideos176
 
Exceptions handling in java
junnubabu
 
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Exception handling in java.pptx
Nagaraju Pamarthi
 
Interface andexceptions
saman Iftikhar
 
L14 exception handling
teach4uin
 
Java exception handling
BHUVIJAYAVELU
 
Exception handling in java-PPT.pptx
sonalipatil225940
 
Exceptions
Soham Sengupta
 
java exception.pptx
SukhpreetSingh519414
 
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java unit 11
Shipra Swati
 
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling in java
Elizabeth alexander
 
Chap2 exception handling
raksharao
 
Ad

Recently uploaded (20)

PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Horarios de distribución de agua en julio
pegazohn1978
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Ad

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

  • #3: 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
  • #4: And many more…
  • #5: 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.
  • #6: All exception classes are subtypes of the java.lang.Exception class. The exception class and error are the subclasses of the Throwable class.
  • #7: try block must be followed by either catch or finally block. You can use multiple catch block with a single try.
  • #8: 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.
  • #9: 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
  • #10: 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-
  • #11: Here are the some sub classes of exception
  • #13: 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.
  • #15: 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...");     }   }  
  • #16: 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"); }} }
  • #17: Only checked exception should be declared