Java/J2EE and SOA (349 Blogs) Become a Certified Professional

Java Exceptions Cheat Sheet – Level Up Your Java Knowledge

Last updated on May 06,2024 13.4K Views

A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

Errors can occur at any time, but what matters is, how we handle and rectify them to maintain the normal flow. Java, being the most prominent object-oriented language, provides a powerful mechanism which allows you to handle these errors/exceptions. Wouldn’t it be wonderful if you had a Cheat Sheet as a quick reference to handle all the exceptions? So, here I bring you the Java Exceptions Cheat Sheet that acts as a solution guide for exception handling.

Related Learning: Java String Cheat Sheet

Java Exceptions Cheat Sheet

Exception Handling in Java is one of the most powerful mechanisms to handle the runtime errors for maintaining the normal flow of an application. When an exceptional condition occurs within a method, Java creates an exception object and throws it. The created exception object contains information about the error, like error type, state of the program etc.

Java_Exceptions_Edureka

Fundamentals of Java Exceptions

What are Exceptions?

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

Types of Exceptions:

  • Checked Exception:
    It is an exception that occurs at the compile time, also called compile time exceptions.
  • Unchecked Exception:
    It is an exception that that occurs at the time of execution. These are also called Runtime Exceptions.

Basic Example of Exception Handling

public class JavaExceptionExample{
  public static void main(String args[]){
    try{
         int data=100/0;
       }catch(ArithmeticException e){System.out.println(e);}
        System.out.println("rest of the code...");
     }
}

Exception Methods

public String getMessage()

// Returns a detailed message about the exception

public String toString()

// Returns the name of the concatenated class with the result of getMessage()

public void printStackTrace()

// Prints the result of toString() along with the stack trace

public stackTraceElement [] getStackTrace()

// Returns an array containing each element on the Stack Trace

public Throwable fillInStackTrace()

// Fills the stack trace by adding previous information present in the stack.

Types of Exceptions in Java

There are 2 types of exceptions:

Built-in  Exceptions

Built-in Java Exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations.

User-Defined Exceptions

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, a user can also create exceptions which are called ‘User-Defined Exceptions’.

Key points to note:

1. A user-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.

// User Defined Exception
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);
 }
}

Exception Handling Methods

try block

Java try block is used to enclose the code that might throw an exception. 

try{  
//code that may throw exception
}catch(Exception_class_Name ref){}

catch block

Java catch block is used to handle the Exception. It must be used after the try block only.

public class Testtrycatch1{  
  public static void main(String args[]){  
    int data=50/0;//may throw exception  
    System.out.println("rest of the code..."); 
  }
}

Nested try block

The try block within a try block is known as nested try block in java.

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");
    }
}

Multi-catch block

If you have to perform various tasks at the occurrence of various exceptions, you can use 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("remaining code");
  }
}
throwthrows
Used to explicitly throw an exceptionUsed to declare an exception
Checked exceptions cannot be propagated using throw onlyChecked exceptions can be propagated
Followed by an instanceFollowed by a class
Used within a methodUsed with a method signature
Cannot throw multiple exceptionsCan declare multiple exceptions
//Java throw example
void a()
{
  throw new ArithmeticException("Incorrect");
}

//Java throws example
void a()throws ArithmeticException
{
  //method code
}

//Java throw and throws example
void a()throws ArithmeticException
{
  throw new ArithmeticException("Incorrect");
}

finally block

finally block is a block that is used to execute important code such as closing connection, stream etc. It is always executed whether an exception is handled or not.

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");
  }
}
finalfinallyfinalize
It is a KeywordIt is a blockIt is a method
Used to apply restrictions on class, methods & variables.Used to place an important codeUsed to perform clean-up processing just before the object is garbage collected
final class cant be inherited, method cant be overridden & the variable value cant be changedIt will be executed whether the exception is handled or not.

finally example where exception occurs and handled

class SampleFinallyBlock{
  public static void main(String args[]){ 
    try{
        int data=25/0;        
        System.out.println(data);
       }
       catch(NullPointerException e)
         {System.out.println(e);}  
       finally {System.out.println("finally block is executed");}  
         System.out.println("remaining code");
  }
}

Exception Handling with Method Overriding in Java

If the superclass method does not declare an exception

If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare the unchecked exception.

import java.io.*; 

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();
 }
}

If the superclass method declares an exception

If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

import java.io.*;  

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){}
}

With this, we come to an end of Java Exceptions Cheat Sheet. Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Comprehensive Java Course Certification training is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming that includes Interfaces, Exception Handling and JDBC Projects.

Related Learning: Java OOP Cheat Sheet

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Java Exceptions Cheat Sheet – Level Up Your Java Knowledge

edureka.co