Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors(such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.) so that the normal flow of the application can be maintained.
Exception:
Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
Major reasons why an exception Occurs:
- Invalid user input
- Device failure
- Loss of network connection
- Physical limitations (out of disk memory)
- Code errors
- Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Differences between Error and Exception :
- Error: An Error indicates a serious problem that a reasonable application should not try to catch.
- Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy:
All exception and error types are subclasses of class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.

Types of Java Exceptions:
- Built-in Exceptions
- Checked Exception
- Unchecked Exception
- User-Defined Exceptions:
- Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.


Difference between Checked and Unchecked Exceptions:
1) Checked Exception:
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception:
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
The advantages of exception handling in java :
- Provision to Complete Program Execution
- Easy Identification of Program Code and Error-Handling Code
- Propagation of Errors
- Meaningful Error Reporting
- Identifying Error Types
Java try and catch:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Syntax:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Multiple Catch Blocks:
Syntax:
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
Finally:
The finally statement lets you execute code, after try...catch
Syntax:
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
throw keyword:
We can throw either checked or unchecked exception. The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.,
throws keyword:
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block. (The Java throws keyword is used to declare the exception information that may occur during the program execution. It gives information about the exception to the programmer. It is better to provide the exception handling code so that the normal flow of program execution can be maintained.)
Differences between throw and throws:
| throw | throws |
|---|---|
| Used to throw an exception for a method | Used to indicate what exception type may be thrown by a method |
| Cannot throw multiple exceptions | Can declare multiple exceptions |
Syntax:throw is followed by an object (new type)used inside the method | Syntax:throws is followed by a classand used with the method signature |
| Example: throw new IOException(“can not open connection”); | Example: throws IOException, ArrayIndexBoundException; |
Methods to print the Exception information:
1.printStackTrace()– This method prints exception information in the format of Name of the exception: description of the exception, stack
trace.
2.toString() – This method prints exception information in the format of Name of the exception: description of the exception.[TBD]
3.getMessage() -This method prints only the description of the exception.
Some runtime exception:
ArtithmeticException:
Data manipulation is a primary function of most Java applications. When data manipulation includes division, developers must be wary of division by zero. If zero ever becomes the denominator in a calculation, Java throws an ArithmeticException.
Example:
int x = 100;
int y = 0; // denominator is set to zero
System.out.println( x/y ); // throws ArithmeticException
NullPointerException:
NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.
These can be:
- Invoking a method from a null object.
- Accessing or modifying a null object’s field.
- Taking the length of null, as if it were an array.
- Accessing or modifying the slots of null object, as if it were an array.
- Throwing null, as if it were a Throwable value.
- When you try to synchronize over a null object.
Example:
String data = null;
System.out.println( data.length() ); // throws NullPointerException
ArrayIndexOutOfBoundsException:
An array in Java requires a set size. If you attempt to add more elements than the array can accommodate, this will result in the ArrayIndexOutOfBoundsException. The following code attempts to add an element to the sixth index of an array that was built to contain only five elements:
String[] data = new String[5];
data[6] = "More Data";
Nullify the NegativeArraySizeException:
Developers must set array size to a positive integer. If a minus sign slips into the array size declaration, this throws the NegativeArraySizeException.
Example:
String[] data = new String[-5]; // throws Runtime Exception
data[1] = "More Data";
Program of Exception Handling:
Refer below blog link.
https://santhiya.home.blog/2022/11/14/exception-program/
Reference:
https://www.javatpoint.com/exception-handling-in-java
https://www.geeksforgeeks.org/exceptions-in-java/
https://www.w3schools.com/java/java_try_catch.asp
https://www.theserverside.com/tip/Fix-these-10-common-examples-of-the-RuntimeException-in-Java
https://www.tutorialspoint.com/java/java_exceptions.htm
https://www.guru99.com/java-exception-throws.html
https://www.programiz.com/java-programming/exception-handling
Leave a comment