SlideShare a Scribd company logo
JAVA EXCEPTIONS CHEAT SHEET Learn JAVA from experts at http://www.edureka.co
Fundamentals of Java Exceptions
Types of Exception in Java with Examples
Exception Hirerachy
In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is
thrown at runtime. Exception Handling is a
mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc.
Exception Handling Methods
Exception Handling with Method Overriding in Java
Throwable
Error
Virtual Machine Error
Assertion Error etc
Exceptions
Checked Exceptions
Example: IO or Compile
time Exception
Unchecked Exceptions
Example: Runtime or Null
Pointer Exception
Object
Java Exceptions
User -Defined Exceptions
Built-in Exceptions
1. Impossible to recover from error.
2.Errors are of type unchecked
exception.
3. All errors are of type java.lang.error.
4.They are not known to compiler.
They happen at run time.
5.Errors are caused by the enviroment
in which the application is running.
1. Possible to recover from Exception.
2.Exceptions can be checked type or
unchecked type.
3.All exceptions are of type java.lang.
Exception
4.Checked exceptions are known to
compiler where as unchecked
exceptions are not known to compiler.
5.Exceptions are caused by the
application.
class MyException extends
Exception{ String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred:
"+str1);
}
}
class Example1{
public static void main(String
args[]){
try{
System.out.println("Start of try
block");
throw new MyException(“Error
Message");
}
catch(MyException exp){
System.out.println("Catch
Block");
System.out.println(exp);
}
}
1.Arithmetic Exception
2.ArrayIndexOutOfBoundException
3.ClassNotFoundException
4.FileNotFoundException
5.IOException
6.InterruptedException
7.NoSuchFieldException
8.NoSuchMethodException
9.NullPointerException
10.NumberFormatException
11.RuntimeException
12.StringIndexOutOfBoundsException
Java throw example
void a(){
throw new ArithmeticException("Incorrect");}
Java throws example
void a()throws ArithmeticException {}
Java throw and throws example
void a()throws ArithmeticException{
throw new ArithmeticException("Incorrect");
}
If the superclass method does not declare an exception
class Parent{
void msg(){System.out.println("parent");}
}
class ExceptionChild extends Parent{
void msg()throws IOException{
System.out.println("ExceptionChild");
}
public static void main(String args[]){ Parent
p=new ExceptionChild();
p.msg();
}
}
Subclass overridden method declares parent
exception
class Parent{
void msg()throwsArithmeticException
{System.out.println("parent");}
}
class ExceptionChild2 extends Parent{
void msg()throws Exception{
System.out.println("child");}
public static void main(String args[]){
Parent p=new ExceptionChild2();
try{
p.msg();
}catch(Exception e){}
}
Exception Handling
User Defined Exceptions
Built-in Exceptions
Java Exceptions
public class ExceptionExample{
public static void main(Stringargs[]){
try{
//code that raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest of the program
System.out.println("rest of the code...");
}
}
Basic Exception
public String getMessage()
public Throwable getCause()
public String toString()
public void printStackTrace()
public StackTraceElement []
getStackTrace()
public Throwable fillInStackTrace()
Exception Methods Common Scenarios
1. ArithmeticException
int a=50/0;
2. NullPointerException
String a=null;
System.out.printn(a.length());
3. NumberFormatException
String s="abc";
int i=Integer.parseInt(s);
4. ArrayIndexOutOfBoundsException
int a[]=new int[5]; a[10]=50;
try - The "try" keyword is used to specify a block where we should place exception code.
catch - The "catch" block is used to handle the exception.
finally - The "finally" block is used to execute the important code of the program.
throw - The "throw" keyword is used to throw an exception.
throws - The "throws" keyword is used to declare exceptions.
try{
//code that throws exception
}catch(Exception_class_Name){}
catch block
public class Sampletrycatch1{
public static void main(String args[])
{
int data=50/0;//throws exception
System.out.println("remaning code");
}
public class SampleMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5]; a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
{System.out.println("task 3 completed");}
System.out.println("remaining code");
}
}
Nested try block
class Exception{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b=59/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5]; a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
System.out.println("other statement);
}catch(Exception e)
{System.out.println("Exception handeled");}
System.out.println("casual flow");
}
}
class SampleFinallyBlock{
public static void main(String args[]){
try{
int data=55/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
System.out.println("remaining code");
}
}
finally finalize
final
try block
Exception Methods
finally block
Multi catch block
Error vs Exception
throw vs throws
final finally finalise
final is a keyword
Used to apply restrictions on
class, methods and variables
• Final class cannot be
inherited
• Final method cant be
overridden’
• Final variable cant be
changed
finally is a block
Used to place
important code
It will be executed
whether the exception
is handled or not
finalise is a method
Used to perform
clean up
processing just
before the object
is garbage
collected

More Related Content

Similar to Java_Exception-CheatSheet_Edureka.pdf (20)

Exeption handling
Exeption handlingExeption handling
Exeption handling
baabtra.com - No. 1 supplier of quality freshers
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exception Handling in java masters of computer application
Exception Handling in java masters of computer applicationException Handling in java masters of computer application
Exception Handling in java masters of computer application
xidileh999
 
exception-handling-in-java programming.ppt
exception-handling-in-java programming.pptexception-handling-in-java programming.ppt
exception-handling-in-java programming.ppt
ansariparveen06
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
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
 
exception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujik
exception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujikexception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujik
exception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujik
anuraggautam9792
 
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
anuraggautam9792
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
chauhankapil
 
exception handling
exception handlingexception handling
exception handling
Manav Dharman
 
how to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppthow to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppt
soneedison007
 
exception-handling,try,catch,throw,throws,finally,errors-in-java.ppt
exception-handling,try,catch,throw,throws,finally,errors-in-java.pptexception-handling,try,catch,throw,throws,finally,errors-in-java.ppt
exception-handling,try,catch,throw,throws,finally,errors-in-java.ppt
ArunPatrickK1
 
Exception Handling ppt slide presentation
Exception Handling ppt slide presentationException Handling ppt slide presentation
Exception Handling ppt slide presentation
madduriradha
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
JAYESHRODGE
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Event handling
Event handlingEvent handling
Event handling
Mohamed Essam
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exception Handling in java masters of computer application
Exception Handling in java masters of computer applicationException Handling in java masters of computer application
Exception Handling in java masters of computer application
xidileh999
 
exception-handling-in-java programming.ppt
exception-handling-in-java programming.pptexception-handling-in-java programming.ppt
exception-handling-in-java programming.ppt
ansariparveen06
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
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
 
exception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujik
exception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujikexception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujik
exception-handling-in-java (1).pptwsedrftgyhujiqawsedrftgyhujik
anuraggautam9792
 
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
anuraggautam9792
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
chauhankapil
 
how to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppthow to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppt
soneedison007
 
exception-handling,try,catch,throw,throws,finally,errors-in-java.ppt
exception-handling,try,catch,throw,throws,finally,errors-in-java.pptexception-handling,try,catch,throw,throws,finally,errors-in-java.ppt
exception-handling,try,catch,throw,throws,finally,errors-in-java.ppt
ArunPatrickK1
 
Exception Handling ppt slide presentation
Exception Handling ppt slide presentationException Handling ppt slide presentation
Exception Handling ppt slide presentation
madduriradha
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
JAYESHRODGE
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 

Recently uploaded (20)

What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdfWhat is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdfHow to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptxMOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWSWomen in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration KeySmadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FMEAutomated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Safe Software
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdfWhat is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdfHow to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptxMOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWSWomen in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration KeySmadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FMEAutomated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Safe Software
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Ad

Java_Exception-CheatSheet_Edureka.pdf

  • 1. JAVA EXCEPTIONS CHEAT SHEET Learn JAVA from experts at http://www.edureka.co Fundamentals of Java Exceptions Types of Exception in Java with Examples Exception Hirerachy In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc. Exception Handling Methods Exception Handling with Method Overriding in Java Throwable Error Virtual Machine Error Assertion Error etc Exceptions Checked Exceptions Example: IO or Compile time Exception Unchecked Exceptions Example: Runtime or Null Pointer Exception Object Java Exceptions User -Defined Exceptions Built-in Exceptions 1. Impossible to recover from error. 2.Errors are of type unchecked exception. 3. All errors are of type java.lang.error. 4.They are not known to compiler. They happen at run time. 5.Errors are caused by the enviroment in which the application is running. 1. Possible to recover from Exception. 2.Exceptions can be checked type or unchecked type. 3.All exceptions are of type java.lang. Exception 4.Checked exceptions are known to compiler where as unchecked exceptions are not known to compiler. 5.Exceptions are caused by the application. class MyException extends Exception{ String str1; MyException(String str2) { str1=str2; } public String toString(){ return ("MyException Occurred: "+str1); } } class Example1{ public static void main(String args[]){ try{ System.out.println("Start of try block"); throw new MyException(“Error Message"); } catch(MyException exp){ System.out.println("Catch Block"); System.out.println(exp); } } 1.Arithmetic Exception 2.ArrayIndexOutOfBoundException 3.ClassNotFoundException 4.FileNotFoundException 5.IOException 6.InterruptedException 7.NoSuchFieldException 8.NoSuchMethodException 9.NullPointerException 10.NumberFormatException 11.RuntimeException 12.StringIndexOutOfBoundsException Java throw example void a(){ throw new ArithmeticException("Incorrect");} Java throws example void a()throws ArithmeticException {} Java throw and throws example void a()throws ArithmeticException{ throw new ArithmeticException("Incorrect"); } If the superclass method does not declare an exception class Parent{ void msg(){System.out.println("parent");} } class ExceptionChild extends Parent{ void msg()throws IOException{ System.out.println("ExceptionChild"); } public static void main(String args[]){ Parent p=new ExceptionChild(); p.msg(); } } Subclass overridden method declares parent exception class Parent{ void msg()throwsArithmeticException {System.out.println("parent");} } class ExceptionChild2 extends Parent{ void msg()throws Exception{ System.out.println("child");} public static void main(String args[]){ Parent p=new ExceptionChild2(); try{ p.msg(); }catch(Exception e){} } Exception Handling User Defined Exceptions Built-in Exceptions Java Exceptions public class ExceptionExample{ public static void main(Stringargs[]){ try{ //code that raise exception int data=100/0; }catch(ArithmeticException e){System.out.println(e);} //rest of the program System.out.println("rest of the code..."); } } Basic Exception public String getMessage() public Throwable getCause() public String toString() public void printStackTrace() public StackTraceElement [] getStackTrace() public Throwable fillInStackTrace() Exception Methods Common Scenarios 1. ArithmeticException int a=50/0; 2. NullPointerException String a=null; System.out.printn(a.length()); 3. NumberFormatException String s="abc"; int i=Integer.parseInt(s); 4. ArrayIndexOutOfBoundsException int a[]=new int[5]; a[10]=50; try - The "try" keyword is used to specify a block where we should place exception code. catch - The "catch" block is used to handle the exception. finally - The "finally" block is used to execute the important code of the program. throw - The "throw" keyword is used to throw an exception. throws - The "throws" keyword is used to declare exceptions. try{ //code that throws exception }catch(Exception_class_Name){} catch block public class Sampletrycatch1{ public static void main(String args[]) { int data=50/0;//throws exception System.out.println("remaning code"); } public class SampleMultipleCatchBlock{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) {System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e) {System.out.println("task 2 completed");} catch(Exception e) {System.out.println("task 3 completed");} System.out.println("remaining code"); } } Nested try block class Exception{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b=59/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);} System.out.println("other statement); }catch(Exception e) {System.out.println("Exception handeled");} System.out.println("casual flow"); } } class SampleFinallyBlock{ public static void main(String args[]){ try{ int data=55/5; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is executed");} System.out.println("remaining code"); } } finally finalize final try block Exception Methods finally block Multi catch block Error vs Exception throw vs throws final finally finalise final is a keyword Used to apply restrictions on class, methods and variables • Final class cannot be inherited • Final method cant be overridden’ • Final variable cant be changed finally is a block Used to place important code It will be executed whether the exception is handled or not finalise is a method Used to perform clean up processing just before the object is garbage collected