SlideShare une entreprise Scribd logo
1  sur  2
Core Java
Cheat Sheet
JAVA EXCEPTION HANDLING CHEAT
SHEET
Learn JAVA from experts at www.edureka.co
Error vs Exception
Fundamentals of Java Exceptions
Types of Exception in Java with Examples
Exception
Hirerachy
Exception Handling
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
Java Exceptions Handling Methods
ExceptionHandling with MethodOverriding 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 ExceptionsBuilt-in Exceptions
1. It is impossible to recover from error
2. All 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
6. Ex: StackOverflow Error,
OutOfException Error
1. It is possible to recover from Excetion
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
6. Ex: ClassCastException, SQLExcetion,
IOException
Basic exception Exceptions Methods Common Scenarios
public class JavaExceptionExample{
public static void main(String
args[]){ try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the
code...");
}
}
public String getMessage()
public Throwable getCause()
public String toString()
public void printStackTrace()
public StackTraceElement[]
getStackTrace()
public Throwable fillInStackTrace()
1. A scenario where ArithmeticException occurs
int a=50/0;//ArithmeticException
2. A scenario where NullPointerException occurs
String s=null;
System.out.printn(s.length());//NullPointer
Exception
3. A scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);//NumberFormat
Exception
4. A scenario where ArrayIndexOutOfBoundsException
occurs
int a[]=new int[5];
a[10]=50;//ArrayIndexOutOfBoundsException
Java Exception Keywords
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.
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("Starting of try
block");
// I'm throwing the custom exception using
throw
throw new MyException("This is My
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 try block
try{
//code that throws exception
}catch(Exception_class_Name){}
Java catch block
public class Sampletrycatch1{
public static void main(String args[])
{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
Solution by exception handling
public class Sampletrycatch2{
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...");
}
}
Java Multi catch block
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("rest of the code...");
}
}
Java nested try example
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(ArrayIndexOutOfBoundsExceptio
n e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("Exception handeled");}
System.out.println("normal flow..");
}
}
final finally finalize
Final is used to apply restrictions on class, Finally is used to place Finalize is used to perform
method and variable. Final class can’t be important code, it will be clean up processing just
inherited, final method can’t be overridden and executed whether exception is before object is garbage
final variable value can’t be changed. handled or not. collected.
Final is a keyword Finally is a block Finalize is a method.
finally block
throw throws
Used to explicitly throw an exception.
Checked exception cannot be propagated using throwonly
Throw is followed by an instance
Throw is used within a method
You cannot throw multiple exceptions
used to declare an exception.
cheked exception can be propagated with throws.
Throws is followed by class.
Throws is used with the method signature.
Java throw example
void m(){
throw new ArithmeticException("Incorrect");
}
Java throws example
void m()throws ArithmeticException{
//method code
}
Java throw and throws example
void m()throws ArithmeticException{
throw new ArithmeticException("Incorrect");
}
class TestFinallyBlock{
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
always executed");}
System.out.println("rest of the
code...");
}
}
If the superclass method does not declare an exception
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild extends
Parent{ void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String
args[]){ Parent p=new
TestExceptionChild(); p.msg();
subclass overridden method declares parent exception
import java.io.*;
class Parent{
void msg()throws
ArithmeticException{System.out.printl- n("parent");}
}
class TestExceptionChild2 extends Parent{
void msg()throws
Exception{System.out.println("child");} public static
void main(String args[]){
Parent p=new
TestExceptionChild2(); try{
p.msg();
}catch(Exception e){}
}

Contenu connexe

Plus de Edureka!

Plus de Edureka! (20)

How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| Edureka
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 
ITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
ITIL® Tutorial for Beginners | ITIL® Foundation Training | EdurekaITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
ITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
 
Difference between ITIL v3 and ITIL 4 | ITIL® Foundation Training | Edureka
Difference between ITIL v3 and ITIL 4 | ITIL® Foundation Training | EdurekaDifference between ITIL v3 and ITIL 4 | ITIL® Foundation Training | Edureka
Difference between ITIL v3 and ITIL 4 | ITIL® Foundation Training | Edureka
 
Jenkins vs Bamboo | Differences Between Jenkins and Bamboo | Edureka
Jenkins vs Bamboo | Differences Between Jenkins and Bamboo | EdurekaJenkins vs Bamboo | Differences Between Jenkins and Bamboo | Edureka
Jenkins vs Bamboo | Differences Between Jenkins and Bamboo | Edureka
 
What Is Digital Marketing? | Digital Marketing Tutorial | Edureka
What Is Digital Marketing? | Digital Marketing Tutorial | EdurekaWhat Is Digital Marketing? | Digital Marketing Tutorial | Edureka
What Is Digital Marketing? | Digital Marketing Tutorial | Edureka
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | Edureka
 
Machine Learning in 10 Minutes | What is Machine Learning? | Edureka
Machine Learning in 10 Minutes | What is Machine Learning? | EdurekaMachine Learning in 10 Minutes | What is Machine Learning? | Edureka
Machine Learning in 10 Minutes | What is Machine Learning? | Edureka
 
Web Development Projects | Web Dev Project Ideas For Beginners | Edureka
Web Development Projects | Web Dev Project Ideas For Beginners | EdurekaWeb Development Projects | Web Dev Project Ideas For Beginners | Edureka
Web Development Projects | Web Dev Project Ideas For Beginners | Edureka
 
What's new in python 3.8? | Python 3.8 New Features | Edureka
What's new in python 3.8? | Python 3.8 New Features | EdurekaWhat's new in python 3.8? | Python 3.8 New Features | Edureka
What's new in python 3.8? | Python 3.8 New Features | Edureka
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Core Java Cheat Sheet | Edureka

  • 2. JAVA EXCEPTION HANDLING CHEAT SHEET Learn JAVA from experts at www.edureka.co Error vs Exception Fundamentals of Java Exceptions Types of Exception in Java with Examples Exception Hirerachy Exception Handling 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 Java Exceptions Handling Methods ExceptionHandling with MethodOverriding 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 ExceptionsBuilt-in Exceptions 1. It is impossible to recover from error 2. All 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 6. Ex: StackOverflow Error, OutOfException Error 1. It is possible to recover from Excetion 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 6. Ex: ClassCastException, SQLExcetion, IOException Basic exception Exceptions Methods Common Scenarios public class JavaExceptionExample{ public static void main(String args[]){ try{ //code that may raise exception int data=100/0; }catch(ArithmeticException e){System.out.println(e);} //rest code of the program System.out.println("rest of the code..."); } } public String getMessage() public Throwable getCause() public String toString() public void printStackTrace() public StackTraceElement[] getStackTrace() public Throwable fillInStackTrace() 1. A scenario where ArithmeticException occurs int a=50/0;//ArithmeticException 2. A scenario where NullPointerException occurs String s=null; System.out.printn(s.length());//NullPointer Exception 3. A scenario where NumberFormatException occurs String s="abc"; int i=Integer.parseInt(s);//NumberFormat Exception 4. A scenario where ArrayIndexOutOfBoundsException occurs int a[]=new int[5]; a[10]=50;//ArrayIndexOutOfBoundsException Java Exception Keywords 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. 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("Starting of try block"); // I'm throwing the custom exception using throw throw new MyException("This is My 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 try block try{ //code that throws exception }catch(Exception_class_Name){} Java catch block public class Sampletrycatch1{ public static void main(String args[]) { int data=50/0;//may throw exception System.out.println("rest of the code..."); } Solution by exception handling public class Sampletrycatch2{ 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..."); } } Java Multi catch block 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("rest of the code..."); } } Java nested try example 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(ArrayIndexOutOfBoundsExceptio n e){System.out.println(e);} System.out.println("other statement); }catch(Exception e){System.out.println("Exception handeled");} System.out.println("normal flow.."); } } final finally finalize Final is used to apply restrictions on class, Finally is used to place Finalize is used to perform method and variable. Final class can’t be important code, it will be clean up processing just inherited, final method can’t be overridden and executed whether exception is before object is garbage final variable value can’t be changed. handled or not. collected. Final is a keyword Finally is a block Finalize is a method. finally block throw throws Used to explicitly throw an exception. Checked exception cannot be propagated using throwonly Throw is followed by an instance Throw is used within a method You cannot throw multiple exceptions used to declare an exception. cheked exception can be propagated with throws. Throws is followed by class. Throws is used with the method signature. Java throw example void m(){ throw new ArithmeticException("Incorrect"); } Java throws example void m()throws ArithmeticException{ //method code } Java throw and throws example void m()throws ArithmeticException{ throw new ArithmeticException("Incorrect"); } class TestFinallyBlock{ 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 always executed");} System.out.println("rest of the code..."); } } If the superclass method does not declare an exception import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class TestExceptionChild extends Parent{ void msg()throws IOException{ System.out.println("TestExceptionChild"); } public static void main(String args[]){ Parent p=new TestExceptionChild(); p.msg(); subclass overridden method declares parent exception import java.io.*; class Parent{ void msg()throws ArithmeticException{System.out.printl- n("parent");} } class TestExceptionChild2 extends Parent{ void msg()throws Exception{System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild2(); try{ p.msg(); }catch(Exception e){} }