Table of Contents
Java exception is one of the most important concepts of Java programming. If you’re a beginner, you should get a basic understanding of how Java exception works and how you can utilize it in your programming. Java Exception is a simple mechanism for handling runtime errors. If we try to understand “exception” in general, it relates to errors that take place while executing a program. Exception handling is also used in C# programming language. So, if you get an idea of how exception handling works in Java, you can easily use it in other programming languages as well.
Learn Coding in your Language! Enroll Here!
The concept of exception handling
At its core, a program is a set of instructions. To run properly, it should not have any logical, runtime, or syntax errors. Whenever a program encounters any runtime error, an exception is raised. The exception object is then thrown by the program, which is handled by the exception handler. Since everything in Java is an object, that means exceptions created by programs are also objects. These objects contain information about the type of exception, as well as additional data that needs to be transmitted.
Example:
#FileNotFoundException
try {
nfile = new File(“abc.txt”);
nfile.readLine;
nfile.write(“another item for the list”);
nfile.close();
} catch (FileNotFoundException fnfe) {
system.out.write(“File not found, Please make sure that the file is present in the location or you are entering the correct file name”);
}
The above is a try-catch code that tries to create a new file. If the creation fails or the file is not present at the current location, the code in the try should throw an exception object. The FileNotFoundException handles the exception object. The coder can either print a statement or perform an action that handles the situation correctly.
Some examples of when exceptions can happen are:
- Dividing by zero
- Accessing Array element with an out of bounds index.
- Passing an incorrect argument to a method.
Java Exceptions Hierarchy
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses – Exception and Error.
The Exception class is used for exception conditions that the application may need to handle. Examples of exceptions include IllegalArgumentException, ClassNotFoundException and NullPointerException.
The Error class is used to indicate a more serious problem in the architecture and should not be handled in the application code. Examples of errors include InternalError, OutOfMemoryError and AssertionError.
Exceptions are further subdivided into checked (compile-time) and unchecked (run-time) exceptions. All subclasses of RuntimeException are unchecked exceptions, whereas all subclasses of Exception besides RuntimeException are checked exceptions.
Learn to code from industry experts! Enroll here
Types of exceptions in Java
Checked Exceptions
Exceptions that can occur at compile-time are called checked exceptions since they need to be explicitly checked and handled in code. Classes that directly inherit Throwable – except RuntimeException and Error – are checked exceptions e.g. IOException, InterruptedException etc.
Here is an example of a method that handles a checked exception:
public void writeToFile() {try (BufferedWriter bw = new BufferedWriter(new FileWriter(“myFile.txt”))) { bw.write(“Test”); } catch (IOException ioe) { ioe.printStackTrace(); }}
In this example, both statements within the try block (the instantiation of the BufferedWriter object and writing to file using the object) can throw IOException, which is a checked exception and therefore needs to be handled either by the method or its caller. In the example, IOException is handled within the method and the exception stack trace is printed to the console.
Furthermore, the BufferedWriter object is a resource, which should be closed when it is no longer needed and closing it can throw an IOException as well. In such cases where closing resources themselves can throw exceptions, using a try-with-resources block is best practice since this takes care of the closing of resources automatically. The example shown earlier uses try-with-resources for exactly this reason.
Unchecked Exceptions
Unchecked exceptions can be thrown “at any time” (i.e. run-time). Therefore, methods don’t have to explicitly catch or throw unchecked exceptions. Classes that inherit RuntimeException are unchecked exceptions e.g. ArithmeticException, NullPointerException.
Here is an example of a method that throws an unchecked exception (NullPointerException) which is not handled in code:
public void writeToFile() {try (BufferedWriter bw = null) { bw.write(“Test”); } catch (IOException ioe) { ioe.printStackTrace(); }}
When the above method is called, a NullPointerException is thrown because the BufferedWriter object is null:
Exception in thread “main” java.lang.NullPointerException at IOExceptionExample.writeToFile(IOExceptionExample.java:10) at IOExceptionExample.main(IOExceptionExample.java:17)
As mentioned, since NullPointerException is an unchecked exception, it did not need to be handled in code – only the checked exception (IOException) was handled.
What is an Error in Java
In Java, an error is a subclass of Throwable that tells that something serious problem is existing and a reasonable Java application should not try to catch that error. Generally, it has been noticed that most of the occurring errors are abnormal conditions and cannot be resolved by normal conditions. As these errors are abnormal conditions and should not occur, thus, error and its subclass are referred to as Unchecked Exceptions. In Java, we have the concept of errors as well as exceptions. Thus there exist several differences between an exception and an error. Errors cannot be solved by any handling techniques, whereas we can solve exceptions using some logic implementations. So, when an error occurs, it causes termination of the program as errors cannot try to catch.
Error Name | Description |
AbstractMethodError | When a Java application tries to invoke an abstract method. |
Error | Indicating a serious but uncatchable error is thrown. This type of error is a subclass of Throwable. |
AssertionError | To indicate that an assertion has failed. |
ClassCircularityError | While initializing a class, a circularity is detected. |
IllegalAccessError | A Java application attempts either to access or modify a field or maybe invoking a method to which it does not have access. |
ClassFormatError | When JVM attempts to read a class file and find that the file is malformed or cannot be interpreted as a class file. |
InstantiationError | In case an application is trying to use the Java new construct for instantiating an abstract class or an interface. |
ExceptionInInitializerError | Signals that tell an unexpected exception have occurred in a static initializer. |
InternalError | Indicating the occurrence of an unexpected internal error in the JVM. |
IncompatibleClassChangeError | When an incompatible class change has occurred to some class of definition. |
LinkageError | Its subclass indicates that a class has some dependency on another data. |
NoSuchFieldError | In case an application tries to access or modify a specified field of an object, and after it, that object no longer has this field. |
OutOfMemoryError | In case JVM cannot allocate an object as it is out of memory, such error is thrown that says no more memory could be made available by the GC. |
NoClassDefFoundError | If a class loader instance or JVM, try to load in the class definition and not found any class definition of the class. |
ThreadDeath | Its instance is thrown in the victim thread when in thread class, the stop method with zero arguments is invoked. |
NoSuchMethodError | In case an application tries to call a specified method of a class that can be either static or instance, and that class no longer holds that method definition. |
StackOverflowError | When a stack overflow occurs in an application because it has recursed too deeply. |
UnsatisfiedLinkError | In case JVM is unable to find an appropriate native language for a native method definition. |
VirtualMachineError | Indicate that the JVM is broken or has run out of resources, essential for continuing operating. |
UnsupportedClassVersionError | When the JVM attempts to read a class file and get to know that the major & minor version numbers in the file are unsupportable. |
UnknownError | In case a serious exception that is unknown has occurred in the JVM. |
VerifyError | When it is found that a class file that is well-formed although contains some sort of internal inconsistency or security problem by the verifier. |
Learn Coding in your Language! Enroll Here!
Difference between Exception and Error
Exception | Error |
Can be handled | Cannot be handled. |
Can be either checked type or unchecked type | Errors are of unchecked type |
Thrown at runtime only, but the checked exceptions known by the compiler and the unchecked are not. | Occurs at the runtime of the code and is not known to the compiler. |
They are defined in Java.lang.Exception package. | They are defined in Java.lang.Error package |
Program implementation mistakes cause exceptions. | Errors are mainly caused because of the environment of the program where it is executing. |
Why is it important to choose Entri?
- Excellent online platform for all the Competitive Exams.
- Provides updated materials created by the Entri Experts.
- Entri provides a best platform with full- length mock tests including previous year question papers.
- You can download the app for free and join the required classes.
- Entri wishes you all the best for your examinations and future endeavours.
“YOU DON’T HAVE TO BE GREAT TO START, BUT YOU HAVE TO START TO BE GREAT.”