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.
- 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.
Java try…Catch block method.:
In Java, a try...catch block is a language construct used to handle exceptions that might occur during the execution of a program. An exception is an error or abnormal condition that occurs during the execution of a program, such as an attempt to access a null object, divide by zero, or access a file that doesn't exist.
Exceptions are represented by objects in Java, and they can be thrown by a method when an error or abnormal condition is detected.
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 }
Java Finally Block :
In Java, the finally block is often used in conjunction with try and catch blocks to handle exceptions and ensure that certain actions are always performed, regardless of whether an exception occurs or not.
The finally block is often used to clean up resources that were allocated in the try block, such as closing a file or releasing a database connection. By using a finally block, you can ensure that the resources are always released, even if an exception is thrown.
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 }
Java throw keyword:
In Java, the throw keyword is used to explicitly throw an exception. It is followed by an instance of the Throwable class or one of its subclasses. When the throw statement is executed, the control is transferred to the catch block that handles the exception.
the keyword is used in the method signature to declare the exceptions that may be thrown by the method. When a method throws an exception that is declared with the throws keyword, the calling method must handle the exception or declare it with the throws keyword as well.
The syntax for Java throw Keyword is:
throw throwableInstance;
Java throws Keyboard
In Java, the "throws" keyword is used in a method signature to indicate that the method may throw one or more types of checked exceptions. When a method is declared with the "throws" keyword, the calling code must handle or declare the checked exceptions that may be thrown by the method.
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
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
Explanation:
Explanation: In this example, the try block contains code that attempts to divide 10 by 0, which will result in an ArithmeticException.
The catch block catches the exception, prints an error message to the console, and continues execution of the program.
Example 2 :Java Program to Check Java finally block
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
Explanation:
The main function is marked with the public static void keywords, which are required to define a main function in Java.
Inside the main function, we've added some code that will run when the program is executed.
In this case, we're calling the divide function with two arguments: 10 and 0.
This will result in an ArithmeticException, which we catch and handle in the catch block.
The divide function is the same as before and is used to demonstrate how an exception can be thrown and caught in the main function.
Note that: To run this code, you'll need to compile and execute it using the javac and java commands, respectively.
Example 3: Java Program to show Exception handling using Java throw
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
Explanation:
We first create a try-catch block to handle the ArithmeticException that occurs when we try to divide 10 by 0.
The catch block prints an error message using the exception's getMessage() method.
Next, we use the "throw" keyword to manually throw a custom Exception object.
We catch this exception in another try-catch block and print its message using the getMessage() method.
Note that: when you use the "throw" keyword, you must throw an object that extends the Exception class or one of its subclasses.
This is because Java's exception handling mechanism is based on objects that represent specific types of errors.
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
Explanation:
We have a "divide" method that takes two integers as input and returns their quotient.
We check if the second input is 0, and if it is, we throw an ArithmeticException with a custom message.
We include the "throws" keyword in the method signature to indicate that the method may throw an ArithmeticException.
When we call the "divide" method in the "main" method, we surround it with a try-catch block to handle the exception that may be thrown.
If we had not included the "throws" keyword in the "divide" method signature, we would get a compile-time error when trying to throw the exception. By including the "throws" keyword, we are explicitly indicating that the method may throw the exception and allowing calling code to handle it appropriately.
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
Login/Signup to comment