Last Updated on April 18, 2023 by Prepbytes
Java is one of the most widely used programming languages in the world. It is known for its robustness and security features. One of the features that contribute to the security of Java is the use of exceptions. Exceptions are errors that occur during the execution of a program. There are two types of exceptions: checked and unchecked exception in Java. In this article, we will discuss checked and unchecked exception in Java along with examples and we will also discuss the difference between checked and unchecked exception in Java.
Checked Exception in Java
In general, a checked exception in Java is anything that has gone wrong in your code and is potentially recoverable. For example, if a client error occurs when using another API, we may retry from that exception to determine if the API is operational again. A checked exception in Java is caught at compile time, so if something throws a checked exception, the compiler will ask you to address it.
Checked Exception in Java Examples
The FileInputStream method from the java.io package is highlighted in red in the code below. The red line indicates that this method throws a checked exception, which the compiler requires us to handle. This can be accomplished in one of two ways.
Implementation of Checked Exception in Java
import java.io.File; import java.io.FileInputStream; public class CheckedException { public void readFile() { String fileName = "file does not exist"; File file = new File(fileName); FileInputStream stream = new FileInputStream(file); } }
Output
Main.java:4: error: class CheckedException is public, should be declared in a file named CheckedException.java
public class CheckedException {
Try Catch
You can simply wrap the code which throws the checked exception in Java within a try-catch block. This now allows you to process and deal with the exception. It’s quite easy to swallow the exception and then go on as if nothing happened with this approach. Later in the code, when what the method was performing is required you may encounter our old buddy the NullPointerException.
By adding our code to the catch block, we have now captured the exception and processed the error in a meaningful way, avoiding the crisis.
Code Implementation
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class CheckedException { public void readFile() { String fileName = "file does not exist"; File file = new File(fileName); try { FileInputStream stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Output
Main.java:4: error: class CheckedException is public, should be declared in a file named CheckedException.java
public class CheckedException {
Throws
We use the keyword throws to throw the checked exception up the stack to the calling method to handle. This is what FileInputStream has just done to you. This looks and feels great – no messy exception code we are writing and we no longer need to handle this exception as someone else can deal with it. The calling method then needs to do something with it … maybe throw again.
As with try catch, be wary of always throwing as you need to think who SHOULD be handling the error and what piece of code is best placed to handle it correctly.
Code Implementation
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class CheckedException { public void readFile() throws FileNotFoundException { String fileName = "file does not exist"; File file = new File(fileName); FileInputStream stream = new FileInputStream(file); } }
Output
Main.java:5: error: class CheckedException is public, should be declared in a file named CheckedException.java
public class CheckedException {
Unchecked Exception in Java
An unchecked exception in Java (also known as a runtime exception) is anything that has gone wrong with the program and cannot be recovered. Because this is not a compile-time exception, you do not need to handle it, but that does not mean you should ignore it.
The most common unchecked exception in Java is the NullPointerException, which occurs when you attempt to access a variable or object that does not exist.
Unchecked Exception In Java Examples
BindException
Because we live in a world where systems are built from lots of small micro services doing their own thing all talking to each other, generally over HTTP, this exception is popping up more and more. There isn’t a lot you can do about it other than find a free port. Only one system can use a single port at any one time and it’s on a first come, first serve basis. Most web applications default to port 8080 so the easiest option is to pick another one.
IndexOutOfBoundsException
This is a very common Java unchecked exception when dealing with arrays. This is telling you; you have tried to access an index in an array that does not exist. If an array has 10 items and you ask for item 11 you will get this exception for your efforts.
Code Implementation
import java.util.ArrayList; import java.util.List; public class IndexOutOfBounds { public static void main(String[] args) { List lst = new ArrayList<>(); lst.add("item-1"); lst.add("item-2"); lst.add("item-3"); var result = lst.get(lst.size()); } }
Output
Main.java:4: error: class IndexOutOfBounds is public, should be declared in a file named IndexOutOfBounds.java
public class IndexOutOfBounds {
^
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The above piece of Java code is a common way to get an IndexOutOfBoundsException. The reason this trips people up is because the size of the array is 3 – makes sense; there are 3 items – but arrays are 0-based so the last item in the array is at index 2. To access the last item, it is always the size -1.
Code Implementation
var result = lst.get(lst.size()-1);
Output
Main.java:1: error: class, interface, or enum expected
var result = lst.get(lst.size()-1);
Checked Exception In Java During Runtime
The following is an example of a microservice architecture that is commonly used. If we receive a request and are unable to read data from our database that is required for this request, the database will throw a checked exception, possibly an SQLException or something similar. We cannot fulfill this request without this data.
This means that there is nothing we can do with this exception to solve the problem, but if we do nothing, the code will continue to execute regardless.
We could throw the exception to the calling code until we reached the top of the chain, at which point we could return the exception to the user. By doing so, we are impacting all the levels above with an exception that they do not care about and should not care about. What we truly need is an unchecked exception to cancel this request.
Code Implementation
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class CheckedException { public void readFile() { String fileName = "file does not exist"; File file = new File(fileName); try { FileInputStream stream = new FileInputStream(file); } catch (FileNotFoundException e) { throw new ProcessingException("Error opening file"); } } } }
Output
Main.java:15: error: class, interface, or enum expected
}
Above we have our same piece of Java code for handling the checked exception thrown from the FileInputStream method but this time we are throwing our own RuntimeException and because this exception isn’t checked at compile time, we don’t need to declare it.
Code Implementation
public class ProcessingException extends RuntimeException { public ProcessingException(String message) { super(message); } }
Output
Main.java:1: error: class ProcessingException is public, should be declared in a file named ProcessingException.java
public class ProcessingException extends RuntimeException {
Declaring your own exception type is as simple as extending the runtime exception class because as we have seen from the diagram at the top, RuntimeException is a subtype of Exception.
Difference Between Checked and Unchecked Exception in Java
To recap, the difference between checked and unchecked exception in Java is as follows:
- A checked exception in Java is caught at compile time, whereas a runtime or unregulated exception in Java is caught at runtime, as the name implies.
- A checked exception in Java needs to be handled by re-throwing or using a try-catch block, but an unchecked exception in Java does not need to be handled.
- A runtime or unchecked exception is a deadly programming error, whereas a checked exception is a condition within your code’s logic that can be recovered or re-tried.
Conclusion
In conclusion, checked and unchecked exception in Java are an important part of the language’s security features. Checked exception in Java is checked at compile-time and are used for recoverable errors, while unchecked exception in Java is not checked at compile-time and are used for unrecoverable errors. Understanding the difference between checked and unchecked exception in Java is important for writing robust and secure Java programs.
FAQs
Here are some frequently asked questions on checked and unchecked exception in Java
Q1: What happens if a checked exception in Java is not handled?
Ans: If a checked exception in Java is not handled then the program will not compile.
Q2: Can we ignore an unchecked exception in Java?
Ans: Technically, an unchecked exception in Java can be ignored, but it is not recommended as it can lead to unexpected behavior in the program.
Q3: Are checked exceptions considered part of the method’s signature in Java?
Ans: Yes, checked exceptions are considered part of the method’s signature in Java.
Q4: Can you throw an unchecked exception in a method that does not declare it in Java?
Ans: Yes, you can throw an unchecked exception in a method that does not declare it in Java.
Q5: Are unchecked exceptions considered part of the method’s signature in Java?
Ans: No, unchecked exceptions are not considered part of the method’s signature in Java.