You are currently viewing Mastering Exception Handling in Java: Tips and Best Practices
Exception propagation in Java

Mastering Exception Handling in Java: Tips and Best Practices

Spread the love

Exception Handling in Java

Exception handling in Java is a mechanism that allows you to handle runtime errors that can occur in your program. It involves catching and dealing with exceptions, which are objects that represent errors that occur during the execution of your code.

When an exception occurs, it interrupts the normal flow of your program and can cause it to crash if it’s not handled properly. By using exception handling, you can catch and handle exceptions, preventing your program from crashing and providing a more stable and robust application.

In Java, exceptions are represented by objects of the Throwable class and its subclasses Exception and Error. The Exception class represents errors that can be handled by your program, while the Error class represents errors that are not recoverable and should not be handled by your program.

Exception Handling in Java
Exception

To handle exceptions in Java, you use a try-catch block. The code that may throw an exception is placed inside the try block, and if an exception is thrown, it is caught by the appropriate catch block based on its type. You can also use a finally block to specify code that should be executed regardless of whether an exception was thrown or not.

In addition to the built-in exception classes in Java, you can also create your own custom exceptions by extending the Exception class or one of its subclasses. This allows you to define your own types of exceptions and handle them in a specific way in your code.

If you are interest

Exception Handling in PHP

Here’s an example of how to use exception handling in Java:

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
} catch (Exception e) {
    // Code to handle any other exception
} finally {
    // Code to be executed regardless of whether an exception was thrown or not
}

Write a program to calculate factorial in java using exception handling

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        try {
            int factorial = calculateFactorial(number);
            System.out.println(number + "! = " + factorial);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

    public static int calculateFactorial(int number) throws IllegalArgumentException {
        if (number < 0) {
            throw new IllegalArgumentException("Cannot calculate factorial of a negative number");
        }
        int result = 1;
        for (int i = 1; i <= number; i++) {
            result *= i;
        }
        return result;
    }
}

This program prompts the user to enter a number and calculates its factorial using the calculateFactorial() method. If the number is negative, an IllegalArgumentException is thrown and caught in the main method, and an error message is printed to the console. Otherwise, the factorial is printed to the console.

Here’s an example output of the program:

Enter a number: 5
5! = 120

And here’s an example output when a negative number is entered:

Enter a number: -5
Cannot calculate factorial of a negative number

Spread the love

Santosh Adhikari

Hello, it's me Santosh Adhikari, from Kathmandu, Nepal. I'm a student of Science and Technology. I love new challenges and want to explore more on Software Quality Assurance. I want to be a professional SQA. I'm also interested in Blogging, SEO activities.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments