Java

Exception Handling In Java

One of the most crucial aspects of Java programming is the ability to manage runtime mistakes brought on by exceptions. You will discover what an exception is, several sorts of it, exception classes, and how to manage exceptions in Java using examples in this manual.

What is an exception?

An unintended occurrence that prevents the program’s regular flow is known as an exception. Program execution is stopped when an exception occurs. We get a system-generated error notice in these circumstances.

The benefit of exceptions is that java developers may manage them in a manner that prevents sudden program termination and ensures that the user receives a useful error message.

As an example, imagine that you are building a software for division where the user inputs both integers. The user may input any number in the following example, but the application will crash and generate an exception if the user enters the second number (the divisor) as 0. This is because dividing an integer by zero has an undefined result. We are use the Scanner class to get user input. Take note of the program’s output.

import java.util.Scanner;
public class JavaExample {

  public static void main(String[] args) {

    int num1, num2;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter first number(dividend): ");
    num1 = scan.nextInt();

    System.out.print("Enter second number(divisor): ");
    num2 = scan.nextInt();

    int div = num1/num2;
    System.out.println("Quotient: "+div);
  }
}

Output:

Exception Handling In Java

As you can see, the program’s Arithmetic error was thrown as a result of user input, however it is not good programming practice to leave such exceptions unhandled. Take care of this exception.

Exception Handling in Java

In this case, we’re attempting to handle the exception that the application mentioned above throws. You can see that the application functioned well and provided a user-friendly error message.

Remember that we have covered the try and catch blocks in depth in other lessons, so don’t worry about them. Just keep in mind that the code that potentially cause an exception must be included inside the try block, and that the catch block comes after the try block and is where the exception error message is set.

import java.util.Scanner;
public class JavaExample {

  public static void main(String[] args) {

    int num1, num2;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter first number(dividend): ");
    num1 = scan.nextInt();

    System.out.print("Enter second number(divisor): ");
    num2 = scan.nextInt();
    try {
      int div = num1 / num2;
      System.out.println("Quotient: "+div);
    }catch(ArithmeticException e){
      System.out.println("Do not enter divisor as zero.");
      System.out.println("Error Message: "+e);
    }

  }
}

Output:

Exception Handling In Java

A system-generated error message is shown to the user and program execution is interrupted if an exception arises that has not been handled by the programmer.

A user will not be able to grasp what went wrong since these system produced messages are not user pleasant. We manage exceptions and explain the cause to them in plain terms. As most of the time, exceptions are caused by incorrect data input by the user, we manage such exceptions and then show a user-friendly warning message to the user, allowing them to fix the issue.

Why we handle the exceptions?

When an exception occurs, exception handling makes sure that the program’s flow doesn’t get interrupted. For instance, if a program has a number of statements and an exception arises midway during the execution of some of those statements, the statements that follow the exception-causing statement will not be executed, and the program will end abruptly. By handling, we ensure that all of the statements run and the program’s execution doesn’t halt.

Why an exception occurs?

A software may throw an exception for any number of reasons. Examples include opening a file that doesn’t exist in your software, a network connection issue, incorrect input data from the user, etc. Here are a few examples:

1. ArithmeticException:

This exception was previously shown in the aforementioned case. This anomaly happens when a number is divided by zero. Any integer may be divided by zero.

int num = 25/0;//ArithmeticException

2. NullPointerException:

when a variable has no value and you are using the variable to conduct an action. For instance, suppose you are comparing a string variable to another string and it includes null. Another instance is when you’re attempting to display a string’s length that includes null.

String str = null;  

//NullPointerException
System.out.println(str.length());

3. NumberFormatException:

This exception happens when the types are different. Consider a scenario where you are attempting to use an arithmetic operator on a string variable.

String str = "beginnersbook.com"; 

//NumberFormatException  
int num=Integer.parseInt(str);

4. ArrayIndexOutOfBoundsException:

when you attempt to access an array index that is larger than the array’s size. We are attempting to access the array’s index 8 (the ninth entry), but it can only hold three elements. When you attempt to access an index that doesn’t exist, an exception happens.

int arr[]=new int[3]; 

//ArrayIndexOutOfBoundsException  
arr[8]=100;

Difference between error and exception

Errors signify that something went wrong that a programmer is unable to fix. You can’t manage a mistake. The error also doesn’t arise because of incorrect data input by the user; rather, it’s a sign of a system failure, disk crash, or resource shortage.

Exceptions are occurrences that happen at runtime as a result of incorrect user input or faulty programming logic. A programmer is capable of handling such situations and making the appropriate corrections. a few instances
When attempting to utilize a reference that leads to null, you get a NullPointerException.
ArithmeticException – When incorrect data is input by the user, such as when attempting to divide a number by 0 since doing so is undefined, this error occurs.
ArrayIndexOutOfBoundsException – Occurs when trying to access an array’s elements outside of their boundaries, such as when the array’s size is 5 (i.e., it contains 5 items) and you are attempting to access the array’s 10th element.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button