Java Exception Handling

Java Exception Handling

What is Java Exception Handling?

  • Exception handling is an important aspect of programming, as it allows developers to detect and handle errors and unexpected situations that may arise during the execution of a program.
  • Java provides a comprehensive mechanism for exception handling, which allows you to catch and handle exceptions using try-catch blocks.
    • You must be familiar with following topics to understand the correspond example Such as: Java try…catch block, Java finally block, Java throw and throws keyword.
  • To understand the Java Exception Handling, Read the Complete Article.

Steps to Check Java Exception Handling:

  • Here are the steps to check Java Exception Handling:
    • Identify the code that may throw an exception.
    • Add a try-catch block to handle the exception.
    • Write code to handle the exception in the catch block.
    • Test the code to see if it throws an exception.
    • Add additional catch blocks as needed.
    • Close any resources that were opened in the try block using the finally block.

The Syntax of Java try.. Catch Method:

try {
    // Code that may throw an exception
} catch (ExceptionType1 e1) {
    // Code to handle the exception of type ExceptionType1
} catch (ExceptionType2 e2) {
    // Code to handle the exception of type ExceptionType2
} finally {
    // Code that will be executed regardless of whether an exception is thrown or not
}

The syntax for Java finally block is:

try {
    // code that may throw an exception
} catch (Exception e) {
    // exception handling code
} finally {
    // code to be executed always
}

The syntax for Java throw Keyword is:

throw throwableInstance;

The syntax for Java throws Keyword is:

accessModifier returnType methodName(parameterList) throws exceptionList {
    // method body
}

Let’s look at the Java Exception Handling to perform certain operations.

Example 1: Java Program Exception handling using try…catch

Run

class Main
{
  
public static void main (String[]args)
  {
    
 
try
    {
      
int result = 10 / 0;	// this will throw an ArithmeticException
    } catch (ArithmeticException e)
    {
      
System.out.println ("Division by zero error: " + e.getMessage ());

} 
} 
}

Output

 Division by zero error: / by zero

Example 2 :Java Program to Check Java finally block

Run

public class Main {
    public static void main(String[] args) {
        // code that runs when the program is executed
        try {
            int result = divide(10, 0);
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }

    public static int divide(int dividend, int divisor) {
        return dividend / divisor;
    }
}

Output

Cannot divide by zero

Example 3: Java Program to show Exception handling using Java throw

Run

public class Main
{
  public static void main (String[]args)
  {
    try
    {
      int num = 10 / 0;		// This will throw an ArithmeticException
    } catch (ArithmeticException e)
    {
      System.out.println ("An error occurred: " + e.getMessage ());
    }

    try
    {
      throw new Exception ("Custom Exception");	// Manually throw a custom exception
    } catch (Exception e)
    {
      System.out.println ("An error occurred: " + e.getMessage ());
    }
  }
}

Output

An error occurred: / by zero
An error occurred: Custom Exception

Example 4: Java Program to show Exception handling using Java throws

Run
public class Main {
  public static void main(String[] args) {
    try {
      divide(10, 0);
    } catch (ArithmeticException e) {
      System.out.println("An error occurred: " + e.getMessage());
    }
  }

  public static int divide(int num1, int num2) throws ArithmeticException {
    if (num2 == 0) {
      throw new ArithmeticException("Division by zero");
    }
    return num1 / num2;
  }
} 

Output

An error occurred: Division by zero

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription