- Java Programming Basics
- Java Tutorial
- Java Environment Setup
- Java Separators
- Java Data Types
- Java Variables
- Java Variable Scope
- Java Type Casting
- Java Operators
- Java Increment Decrement
- Java Left Shift
- Java Right Shift
- Java Bitwise Operators
- Java Ternary Operator
- Java Control Statements
- Java if-else statement
- Java for Loop
- Java while Loop
- Java do-while Loop
- Java switch Statement
- Java break Statement
- Java continue Statement
- Java Popular Topics
- Java Arrays
- Java Multidimensional Array
- Java Strings
- Java Methods
- Java Date and Time
- Java Exception Handling
- Java File Handling
- Java OOP
- Java Classes and Objects
- Java Constructors
- Java Constructor Overloading
- Java Object as Parameter
- Java Returning Objects
- Java Encapsulation
- Java Abstraction
- Java Inheritance
- Java Polymorphism
- Java Packages
- Java Import Statement
- Java Multithreading
- Java Suspend Resume Stop Thread
- Java Programming Examples
- Java Programming Examples
Java exception handling with an example program
Java is a well-known programming language that can be used to create robust and dependable software applications. Even the best-written code can encounter errors or unexpected events during execution. This is where exception handling comes into play. Exception handling in Java enables developers to anticipate and gracefully handle errors, ensuring that their programs continue to run smoothly even when unexpected problems arise.
In this article, we'll look at the fundamentals of Java exception handling and provide some sample programs to get you started.
In Java, exception handling is the mechanism that allows developers to handle runtime errors or exceptions that occur during program execution. Exception handling allows a program to handle unexpected situations gracefully, preventing the program from crashing or behaving unexpectedly.
In Java, exception handling is accomplished by combining the try, catch, and finally keywords. The code in the "try" block may throw an exception, and the code in the "catch" block handles the exception. The "finally" block is optional and contains code that is executed whether or not an exception is thrown.
In general, exception handling in Java entails using a try-catch along with the finally block, as shown below:
try { // Code block that may throw an exception } catch (ExceptionType1 e1) { // ExceptionType1 exception handler } catch (ExceptionType2 e2) { // ExceptionType2 exception handler } finally { // Whether or not an exception was thrown, this optional block of code must be executed }
We can have multiple "catch" blocks.
The try block in this form contains the code that may potentially throw an exception. The catch blocks define what to do when a specific type of exception is thrown, and the finally block contains code that is executed whether or not an exception is thrown.
Java exception handling example
Consider the following program as an example demonstrating the exception handling in Java:
import java.util.Scanner; public class MyClass { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the numerator: "); int numerator = scanner.nextInt(); System.out.print("Enter the denominator: "); int denominator = scanner.nextInt(); try { int result = divide(numerator, denominator); System.out.println("\nResult: " + result); } catch (ArithmeticException e) { System.out.println("\nAn error occurred: " + e.getMessage()); } catch (Exception e) { System.out.println("\nAn unknown error occurred: " + e.getMessage()); } finally { System.out.println("\n\nProgram completed!"); } } public static int divide(int a, int b) { return a / b; } }
When we execute the above Java program, we will get the output shown in the snapshot given below:
Now type the numerator value, let's say 12, and hit the ENTER key. Then type the denominator value, let's say 3, and hit the ENTER key to get the following output:
Now if we try with a denominator value of 0, then we will get the following output:
The divide method is wrapped in a try block because division by zero is undefined and will result in an ArithmeticException. If an ArithmeticException is thrown during the division operation, the program will use the first catch block to catch the exception and print a user-friendly error message.
If an exception of another type is thrown during the division operation, the program will catch it with the second catch block and print a generic error message. Regardless of whether an exception was thrown or not, the finally block will always be executed and will print a message indicating that the program has completed.
The following figure depicts the top-level exception hierarchy:
Java exception types: built-in exceptions
Here is a list of some of the more typical Java exception types along with a short description:
- ArithmeticException: When an arithmetic operation fails, such as when dividing by zero, the ArithmeticException exception is raised.
- NullPointerException: When an object is needed but a null reference is used, the NullPointerException exception is raised.
- ArrayIndexOutOfBoundsException: The ArrayIndexOutOfBoundsException is raised whenever an out-of-bounds index is used to access an array.
- IllegalArgumentException: This exception is raised when an illegal argument for example, a negative value for a parameter that calls for a positive value is passed to a method.
- NumberFormatException: When a string cannot be translated into a numeric value, the NumberFormatException exception is raised.
- ClassCastException: When an object is cast to a type that is incompatible with its original type, a ClassCastException is raised.
- IOException: When an I/O operation fails, like when reading from or writing to a file, the IOException exception is raised.
- InterruptedException: When a thread is interrupted while it is waiting or sleeping, the InterruptedException exception is thrown.
- SecurityException: When a security breach takes place, such as when accessing a restricted resource, the SecurityException exception is raised.
- RuntimeException: RuntimeException is the superclass of all exceptions that may be thrown while a Java application is running normally. This covers errors like the IllegalArgumentException, NullPointerException, and ArithmeticException.
- ClassNotFoundException: When an application tries to load a class using its string name but the class cannot be found, a ClassNotFoundException is raised.
- IllegalStateException: When a method is called at the wrong time or in the wrong state, the exception IllegalStateException is raised.
- StringIndexOutOfBoundsException: When an index for a string is outside its acceptable range, an exception called StringIndexOutOfBoundsException is raised.
- DateTimeException: This exception is raised whenever a date- or time-related processing error takes place.
« Previous Tutorial Next Tutorial »