Exceptions vs Errors in Java
Learn via video course
Overview
An Error is a severe situation generated when the user performs an unexpected operation. An Exception is an event that occurs during the program execution and disrupts the normal flow of the program's execution. Errors mostly happen at compile-time like syntax error; however it can happen at runtime as well. Whereas an Exception occurs at runtime (checked exceptions can be detected at compile time). Both Error and Exception have the same parent class as Throwable.
Scope
- This article explains the differences between an Error and an Exception in Java, along with the types and their respective examples.
- This article does not include exception handling.
Introduction
An error is an incident that gets generated when some unexpected scenario is encountered due to the user's input or due to some events which were not thought of while writing the code. It may be due to the programmer's mistake or some over or under-estimated conditions. For example, syntax errors are compile-time errors that occur due to a programmer's carelessness.
On the other side, an Exception is an incident that can disrupt the program's current flow (or instructions) and change its direction to keep the program working because the incident could terminate the program abruptly and maybe crash the entire system as well.
If an error is just a software bug generated inside computer hardware, how serious can the impact of an error be?
An error can be hazardous if it occurs at a crucial and dangerous place. People have died for real due to failures of real-life computer-based devices. Financial sectors lose millions and billions due to these errors. List of Software Bugs.
Errors to Exceptions
Researchers in the tech industry analyzed the reasons behind the failures of real-world software & hardware devices and found out there were errors in the programs used in the devices. They found out some unique scenarios in programs that can lead to error and gave them the name of exceptions, so that if in the future that condition tries to happen again, then the compiler or the program halts the compilation or execution and terminates the program so that some disastrous event can be prevented if there might be chances of its creation.
These special error scenarios which have been encountered or predicted in advance are known as exceptions. Handling these special error scenarios gave rise to a new field in computer science which is known as Exception Handling.
The image shown below depicts the hierarchy of Error and Exception classes.
Which came first, error or exception?
Errors came first, the people started analyzing the reasons behind errors, which gave rise to exceptions.
Definition of Exception
An Exception is the occurrence of an event that can disrupt the normal flow of the program instructions. Exceptions can be caught and handled in order to keep the program working for the exceptional situation as well, instead of halting the program flow. If the exception is not handled, then it can result in the termination of the program. Exceptions can be used to indicate that an error has occurred in the program.
When an exception occurs, it creates an exception object. It holds information about the name and description of the exception and stores the program's state when the exception occurred.
The below image shows the flow of an exception.
There are 2 types of Exceptions:
- Checked Exceptions
- Unchecked Exceptions
Checked Exceptions
Exceptions that occur and can be detected at compile time are known as Checked Exceptions. These exceptions prevent the program from running, and so they must be handled by the programmer. Otherwise, the program will not get compiled.
For example, ClassNotFoundException, FileNotFoundException, IOException, SQLException, etc.
Unchecked Exceptions
Exceptions that occur at the time of the program execution, i.e., at runtime, are known as Unchecked Exceptions. These exceptions are ignored at the time of compilation.
They occur due to the following main reasons:
- Invalid User Input
- Bugs in the program
- Improper usage of an API
- Memory limit exceeded
Examples of unchecked exceptions include ArrayIndexOutOfBoundsException, NullPointerException, IllegalArgumentException, ArithmeticException, NumberFormatException, etc.
Examples of Exception
- Checked Exception: In the below example, we are using the sleep() function of the thread class, which throws a checked exception named InterruptedException, but we have not knowingly handled the exception.
Output:
Explanation:
As the method sleep() of Thread class requires throwing an InterruptedException, and we have not thrown it or used try-catch block to handle it, so the program terminated abruptly with the above error.
- Unchecked Exception: In the below example, we perform division by 0, which is an illegal operation.
Output:
Explanation:
Since division by 0 is an illegal operation, which should be handled by throwing an ArithmeticException, the program terminated with the above error message, as it requires the programmer to handle such divisions using ArithmeticException.
Benefits of Exception
By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques:
Separate Error Handling Code from "Regular" Code
It helps to separate error handling code from regular code. This error-handling code can be used to run a set of instructions that can be defined earlier to handle the situation. Let us understand it with the help of the following example of reading a file.
Operations performed while reading a file can be as follow:
readFile() {
- open the file;
- determine its size;
- allocate that much memory;
- read the file into memory;
- close the file;
}
Exceptional Cases:
- What to do if the file can't be opened?
- What to do if the length of the file can't be determined?
- What to do if sufficient memory can't be allocated?
- What to do if the reading of the file fails?
- What to do if the file can't be closed?
In order to handle these cases, the readFile() function has to detect the error, report it and handle it.
Propagating Errors Up the Call Stack
Exceptions provide the ability to propagate errors up the call stack of methods. Let us understand it with the help of an example.
Let's say that the readFile() function used in the previous section is the fourth function in a series of nested function calls made by your main program: function1 calls function2, which calls function3, which finally calls the readFile() function.
Suppose that function1() is the only function interested in the errors that might occur within the readFile() function. Let us now see how Exception handling in Java has an advantage over Traditional error notification techniques in this scenario.
- Traditional error-notification techniques force function2() and function3() to propagate the error codes returned by the readFile() function up the call stack until the error codes finally reach function1() — the only function that is interested in them. Pseudo-code implementing this situation is shown below.
- Java Exception Handling Mechanism will search backward in the call stack to find any method that can handle the exception. Thus only the methods that care about errors have to worry about detecting errors. This is shown in the pseudo-code below.
Definition of Error
Error is an unexpected event that cannot be handled at runtime. Errors can terminate your program. Most of the time, programs cannot recover from an error. Errors cannot be caught or handled. They are generally caused by the environment in which the code is running. e.g, The image below is seen by almost all the computer users.
Handling an error is out of the scope of a program. It can be handled externally.
There are 3 types of Errors:
- Syntax Error
- Runtime Error
- Logical Error
Syntax Errors
Syntax Errors are those errors detected during the compilation phase by the compiler when your code does not follow the syntactical rules of the programming language you are using. e.g, missing semi-colon(s), missing parenthesis, using else if() block directly without using if block first, returning nothing from the function when the return type is some data type, say, int, etc.
Example
In the below example we are trying to find out if a number n is even or odd.
Output:
Explanation:
Since we have used else if and else condition blocks without providing an if condition block, which is a syntax error, so the compilation is terminated.
Runtime Errors
Runtime Errors occur during the execution of a program, due to lack of system resources, or due to irrelevant input by the user. The compiler has no idea whatsoever how to detect these kinds of errors. For example, dividing a number by 0, accessing an element from an array that is out of range, trying to convert an invalid string to an integer, out of memory error, etc.
Example
In the code below, we are trying to find the count of the odd numbers present in an integer array.
Output:
Explanation:
Since we have used 'i <= arr.length' and in java arrays have 0 based indexing, so arr[i] for i = arr.length is an illegal operation as no such index exists, which throws a runtime error.
Logical Errors
Logical Errors are those errors where the program returned incorrect results when you were expecting the desired result. These occur due to some mistake in the code logic made by the programmer. The compiler cannot detect these errors. The user can just understand them after seeing the output. These are also known as Semantic Errors.
For example, When the programmer writes mistakenly, if(i = 1) instead of, if(i == 1): This will change the program's narrative.
Example
In the below example, we are trying to find out the XOR (Exclusive OR) of all elements from 1 to 5.
Output:
Note:
The expected output is:
Xor of all numbers is: 1
Explanation:
The actual output is different from the expected output because in the above code, a semi-colon is used after the for loop, which ultimately leads to just incrementing i up to 6 when the condition breaks, and after that, it runs the statement of the xor operation, which just runs only once and that also for i = 6. Hence the output is 6, which should have been 1, which is the correct xor of all the numbers from 1 to 5.
Difference Between Error and Exception in Java
Error | Exception |
---|---|
An error cannot be handled at runtime. | An exception can be handled at runtime |
An error can occur both at compile time and during runtime. | Although all the Exceptions occur at runtime. But checked Exceptions can be detected at compile time. |
There are 3 types of Errors: Syntax Error, Runtime Error and Logical Error | There are 2 types of Exceptions: Checked Exceptions and Unchecked Exceptions |
An error has the capacity to terminate your program and maybe your system as well. | An exception has the capacity to distract the normal flow of the program and change its direction to somewhere else when an exceptional case has occurred. |
An Error is such an event that no one can control or guess when it is going to happen. | An Exception can be guessed, handled, and utilized in order to change the original flow of the program. |
An Error can be thought of as an explosion that happens when there is no defense or checks against a particular failure condition. | An Exception can be thought of as a last line of defense to prevent errors. |
Key Difference: Error Vs Exception
An Error indicates serious problems that a reasonable application should not try to catch. Error is something you cannot predict, catch, or handle most of the time. It breaks your program's flow. A programmer wants to avoid as many errors as possible.
On the other hand, An Exception indicates conditions that a reasonable application might want to catch. The exception was meant to give you an opportunity to do something with it, like try once more or try something else or write to the log. A programmer wants to handle as many exceptions as possible.
e.g,
Conclusion
- Errors occur at compile time and run time, which can terminate the compilation or execution.
- Exceptions occur only at run time, just that checked exceptions can be detected at compile time.
- Errors are also unchecked like Runtime Exceptions.
- Exceptions provide you the opportunity to make your program run in normal flow.
- Code should be in such a way that it has very few errors and a high number of managed exceptions.
- Error is an irrecoverable condition. However, we can recover from an exception.