Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Exceptions are errors that occur in Java to interrupt the normal process of a program. They are triggered when an error happens at the time of execution, such as, when the user is performing a mathematical operation by dividing a number by zero or making an attempt to open a file that does not exist in the system. There is a mechanism in Java to deal with such exceptions and the program does not crash in a sudden way.
The various types of exceptions in Java are what we will look at in this article and they include built-in exception which is the Java exceptions and user-defined exception which are exceptions that we ourselves can create. As well, we will also cover some of the major differences between checked & unchecked exceptions.
Java Built In Exceptions
Java has a good number of predefined exceptions that deal with frequent errors during a program. These exceptions belong to the standard library of Java, therefore, we do not necessarily have to declare them. They assist us in finding where we have something wrong in our code.
Built-in exceptions in Java are divided into two main types:
Checked Exceptions (Compile-time exceptions)
Unchecked Exceptions (Runtime exceptions)
Compile-time exceptions (Checked Exceptions)
Checked exceptions are checked by the compiler at compile time. If a method throws a checked exception, we must handle it using try-catch or declare it using throws.
Let us see them one by one with examples.
1. Checked Exceptions
Compile time checks, checked exceptions are the exceptions checked by the compiler at compile time. In case an approach throws a checked exception, we have to deal with it with the aid of a try-catch or state throws.
As an example, FileNotFoundException (When attempting to read a file that is not there)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("nonexistent.txt");
Scanner scanner = new Scanner(file); // This line throws FileNotFoundException
System.out.println("File read successfully.");
} catch (FileNotFoundException e) {
System.out.println("Error: File not found.");
}
}
}
You can also try this code with Online Java Compiler
We have to deal with FileNotFoundException on behalf of the compiler.
Without using try-catch or throws, we can not compile the code.
2. Unchecked Exceptions
Unchecked exceptions do not check at a compile time. They arise as a result of bug errors in the code.
Example: ArithmeticException (Dividing by zero)
public class UncheckedExceptionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a / b); // This throws ArithmeticException
}
}
You can also try this code with Online Java Compiler
Exception in thread "main" java.lang.ArithmeticException: / by zero
In the present code:
The compiler does not bother us to cope with ArithmeticException.
All the programs are compiled but they crash up at runtime.
Java Exceptions that are User-Defined
There are situations when the built-in exception of Java is not satisfactory to our demands. Most of the time in real project we tend to create our own exceptions in dealing with certain errors. These are referred to as user-defined exceptions.
What is the Way to Develop a Custom Exception?
Extend Exception (checked exceptions)
Should be managed via try catch or throws.
Subclass RuntimeException (in case of unchecked exceptions)
Nor enforced treatment by the compiler.
Example: Age Validation Exception
Suppose we are creating a very simple voting system and allowing only people of age 18 years. We will design a special exception InvalidAgeException.
Step 1: Define Custom Exception
// Custom checked exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); // Pass error message to parent class
}
}
You can also try this code with Online Java Compiler
public class VotingSystem {
public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above to vote.");
} else {
System.out.println("You are eligible to vote!");
}
}
public static void main(String[] args) {
try {
checkAge(16); // This will throw InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
You can also try this code with Online Java Compiler
Can make code verbose due to mandatory try-catch blocks, but improve documentation and error awareness.
Keep code cleaner and simpler as handling them is optional.
Debugging Difficulty
Easier to debug due to predictable nature and informative error messages.
Harder to debug as they are often unexpected and may not have universal error handling.
Application Stability
Enhances application stability by enforcing proper error handling and recovery.
Can reduce application stability if not handled properly; may cause the application to crash.
Frequently Asked Questions
What will occur when I do not handle a checked exception?
Unless you deal with a checked exception (with either try-catch or throws), your program will fail to compile. Java compiler makes you handle the exceptions which are checked in order to avoid possible run time failures.
Is it possible to declare my custom exception unchecked?
Yes, by deriving RuntimeException, and not Exception. This causes your exception to be an unchecked exception, i.e. not in any way enforced to be handled by the compiler. Application of it should be when the exception is not a failure by the external operation but the programmer instead.
What is the advantage of checking exceptions and unchecked exceptions in Java?
Check exceptions will make sure vital faults (such as lacking files) are dealt with. Uncaught exceptions are so that programming errors (such as null pointer) can be handled, but doing so forcedly may unnecessarily complicate code. The difference assists in creating cleaner and safer programs.
Conclusion
In this article we came to know about the exceptions in Java. We have seen that Java offers some exception classes such as NullPointerException or FileNotFoundException used to manage the simple mistakes. Another topic that we covered was how we can write our own custom exceptions when we want to deal with a particular type of exception.The major distinction between checked and unchecked exceptions is that when we have checked exceptions they have to be dealt with, whereas when we have unchecked exceptions, we do not explicitly need to deal with exceptions. The presence of checked exceptions allows excluding errors caused by external factors, whereas unchecked exceptions are most often related to code bug