An exception (or an exceptional occasion) is a situation that occurs when executing the program. When an exception occurs, the normal process of the program gets interrupted and the application/program ceases to run in a way that isn’t recommended, so it is imperative that these exceptions be dealt with.
Exception handling in Java is a situation that unusual the result of numerous reasons. Here are some instances in which an exception may occur. The handling of exceptions is among the most significant features of Java programming, which lets us handle problems that arise from exceptions.
Why do we Need Exception?
An individual has entered insufficient information. A file that must be opened is not found. A network connection is lost during a communication either because the JVM has exhausted its memory.
These exceptions may be due to errors by the user, some due to programming errors, and some due to physical resources that have not worked in a certain way.
What is Exception Handling in Java?
The exception handling in Java is a most effective ways to handle problems that occur during execution so running of application be preserved.
Here we will discuss Java exceptions, its kinds, and differences between unchecked and checked exceptions. A problem is an incident that interrupts the normal operation that the software. If an exception occurs, program execution ceases.
Exception vs Error
Exception: Exceptions indicate conditions that an application with a reasonable chance of try to identify. It’s an object which is a wrapper for an error event that was triggered by the course of a procedure and is transmitted into the running system. In Java exceptions, they are utilized to identify different kinds of error-related conditions.
Error: A Error is a the existence of a serious issue that an application shouldn’t try to detect. Errors are a sign that something serious enough has gone wrong. The application should be shut down instead of attempt to correct the error.
Let’s say you’ve coded an application that connects to the server. It worked as expected as you worked on the program. In the production phase the server was down. When your application tried to connect to it, an exception was raised.
Java Exception Handling
As far as we’ve seen an exception that is out of the development’s control. However, blaming the code’s failure on environmental causes isn’t an option. You require a Robust Programming system that handles extraordinary circumstances. This code is referred to as an Exception Handler.
In our scenario, the best way to handle an exception is in the event that your server goes down make sure to make sure to connect the backup server.
To do this, type in your server’s code (Using traditional if and when conditions).
Know How to Handle Exception?
Check whether the server is not working. If it is, then compose the code to connect with the server that is backup. This type of code organization by using an if and else loops, is not efficient when you have multiple Java exceptions to deal with.
{class connectclass connect
if(Server Up){is
}
{elseOther than that
}
}
Try Catch Block
Java offers an inbuilt, exceptional handling.
The normal code is put into TRY block.
The code for handling exceptions goes into the CATCH block.
In our case, the TRY block contains the code to establish a connection to the server. CATCH block contains the code for connecting with the server that is backing up.
If the server is online the code contained in the CATCH block is not considered. If that the server goes down an exception is raised and the code contained in the catch block is executed.
Advantage of Exception Handling in Java
The main benefit of handling exceptions is to ensure the normal operation that the app follows. The most common reason for an exception is that it interferes with the normal operation of the application. This is the reason we have to manage exceptions.
Exception handling is designed to ensure that the program’s flow doesn’t end when an unexpected event occurs. For instance in the case of a program that has a several statements, and an error occurs midway through the execution of certain statements, the statements that follow the exception won’t be executed while the application will stop abruptly.
Through handling, we ensure that all statements are executed and that the program’s flow isn’t interrupted.
Different Types of Exceptions
Exceptions are Two Types in Java:
1) Checked the exceptions
2) Unchecked exceptions
I’ve gone over this in depth in another Checked and Unchecked instances of exceptions within Java.
1) Checked Exceptions
All exceptions , other than Runtime exceptions are referred to as checked exceptions since the compiler will check the exceptions during compilation to determine whether the programmers have taken care of them properly or not. They cannot be ignored. The programmers must be aware of (handle) exceptions. If exceptions aren’t addressed or declared within the program, you’ll receive a compilation error. For example, SQLException, IOException, ClassNotFoundException etc.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo{
public static public static main(String args[]) {public static void main (String args[])
File file = new File(“E://file.txt”);
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
2) Unchecked Exceptions
Runtime Exceptions are also referred to as Unchecked exceptions. These exceptions do not get evaluated at compile time, so the compiler doesn’t know if the programmer is handling the exception or not, but it is the programmers responsibility to manage these exceptions and offer the safe exit. This can include programming errors including mistakes in logic or incorrect application or misuse of an API. Runtime exceptions are not considered when compiled. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
{public class Unchecked_Demo public class Unchecked_Demo
public static public static main(String args[]) {public static void main(String args[])
integer number[] 1,2, 3, 4;
System.out.println(num[5]);
}
}
If you compile and run the program above and run it, you will see the following error.
Output
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Java Exception Keywords
Java offers five keywords that can be employed to handle exception. The table below explains each.
Keyword Description
Try Keyword: Try keyword is used to identify a block on which we need to put the exceptions code. This means that we cannot use the try block on its own. The try block should be followed by catch or, finally.
Catch Keyword: Catch block is used to handle an exception. It has to be preceded by try block. This means that it is not possible to use the catch block on its own. It could be followed by the block after.
Finally Keyword: Finally block is used to run the programming code. It will be executed regardless of regardless of whether an exception is handled or not.
Throw Keyword: The throw keyword is used to throw an exception or used to indicate exceptions. It states that there might occur an exception during the procedure. It doesn’t throw an error. It’s always used in conjunction with method signature.
Java Exception Handling Example
Let’s look at an example of Java Exception Handling in which we’re using the try-catch method to handle an exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static empty main(String args []){
{tryTry it!
//code that could cause exception
int data=100/0;
}catch(ArithmeticException e)
//the rest of the code in the program
System.out.println(“rest of the code…”);
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
The rest part of code…
In the example above 100/0 causes an ArithmeticException that is dealt with by the try-catch block.
Java Hierarchy of the Exception Class
When one catch phrase is executed and the other catch statements fail, they are omitted and the execution continues following the attempt/catch block. The catch blocks that are nested follow the Exception hierarchy.
Java Exception Hierarchy
Every exception class within Java expand the classes “Throwable”. Throwable comes with two subclasses: Error and Exception.
The class Error describes the situation or difficulties that are not anticipated to be encountered in normal situations in our program, for example hardware error, memory errors, JVM error, etc
A runtime exception is a subclass of the class called exception. This type of exception refers to an exception that occurs during the execution time and are not recorded at time of compilation. One excellent example is the divide by zero exception also known as null pointer exception or null pointer exception,
IO exceptions are created in the input and output. Interrupted exceptions, in Java are generated by multiple threads. Download and install Java JDK packages here step-by-step to use it.
User-defined Exceptions
You can write your own exceptions using Java. Be sure to keep these points in mind while writing the classes for your exceptions. If you are looking to create an exception that is checked and automatically enforced in the Handle or Declare Rule, you must extend the Class Exception.
If you wish to write a runtime exception you must expand the class RuntimeException.
Our own definition of exception class by following the steps below:
class MyException extends Exception {
}
It is enough to extend the exception class for your personal exception. These are regarded as checked exceptions. Here Insufficient FundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is just like any other class, with helpful fields, methods and fields.