Exceptions are events that disrupt the normal flow of a program. They occur when something unexpected happens, like dividing a number by zero or trying to access an array index that doesn't exist. Java has built-in exceptions to handle these situations.
In this article, we'll talk about Java's built-in exceptions, user-defined exceptions, & the difference between checked & unchecked exceptions. You'll learn how to handle exceptions effectively in your Java programs.
Java Built-in Exceptions
Java has many built-in exceptions that are ready to use. These exceptions cover common error scenarios. For example, the ArithmeticException is thrown when you try to divide a number by zero. Here's how it looks in code:
Java
Java
public class ArithmeticExceptionExample { public static void main(String[] args) { int number = 10; int divisor = 0;
try { int result = number / divisor; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Division by zero!"); } } }
You can also try this code with Online Java Compiler
In this code, we try to divide the `number` by `divisor`, which is zero. This throws an ArithmeticException. We catch the exception using a try-catch block & print an error message.
Output
ERROR!
Error: Division by zero!
Another common built-in exception is the NullPointerException. It occurs when you try to access a method or variable on a null object reference. Here's an example:
Java
Java
public class NullPointerExceptionExample { public static void main(String[] args) { String text = null;
In this case, we try to call the `length()` method on a null `text` reference, which throws a NullPointerException. We catch the exception & handle it appropriately.
Java User-Defined Exceptions
Sometimes, the built-in exceptions in Java might not be enough for your specific needs. In such cases, you can create your own custom exceptions, known as user-defined exceptions.
To create a user-defined exception, you need to extend the Exception class or one of its subclasses.
For example:
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
In this code, we define a custom exception called InvalidAgeException. It extends the Exception class & has a constructor that takes an error message.
Now, let's see how to use this custom exception in a program:
Java
Java
class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } }
public class CustomExceptionExample { public static void validateAge(int age) throws InvalidAgeException { if (age < 0 || age > 120) { throw new InvalidAgeException("Invalid age: " + age); } System.out.println("Valid age: " + age); }
In this example, we have a `validateAge()` method that checks if the given age is valid. If the age is less than 0 or greater than 120, we throw an InvalidAgeException with a custom error message.
In the `main()` method, we call `validateAge()` with different age values. If an InvalidAgeException is thrown, we catch it & print the error message.
Difference between Checked and Unchecked Exception:
Checked Exceptions
Unchecked Exceptions
Checked exceptions are checked at compile-time.
Unchecked exceptions are not checked at compile-time.
They extend the Throwable class directly or indirectly, except for RuntimeException & its subclasses.
They extend the RuntimeException class or its subclasses.
Checked exceptions must be declared in the method signature using the throws keyword or handled using a try-catch block.
Unchecked exceptions do not need to be declared or handled explicitly.
They represent exceptional conditions that a well-written application should anticipate & recover from.
They represent programming errors, such as logic errors or improper use of an API.
Checked exceptions are used for predictable & recoverable error scenarios, such as file not found or network connection failure.
Unchecked exceptions are used for unpredictable & unrecoverable error scenarios, such as dividing by zero or accessing a null object reference.
Handling checked exceptions is mandatory, either by catching them or declaring them in the method signature.
Handling unchecked exceptions is optional, but it's good practice to catch & handle them appropriately.
Propagating checked exceptions requires explicit declaration in the method signature.
Propagating unchecked exceptions does not require explicit declaration.
Frequently Asked Questions
Can we create our own checked exceptions?
Yes, you can create custom checked exceptions by extending the Exception class directly.
Is it necessary to handle unchecked exceptions?
While not mandatory, it's good practice to handle unchecked exceptions to prevent program crashes.
Can we throw an exception manually?
Yes, you can throw exceptions manually using the throw keyword followed by an exception object.
Conclusion
In this article, we learned about Java's built-in exceptions, user-defined exceptions, & the difference between checked & unchecked exceptions. Built-in exceptions handle common error scenarios, while user-defined exceptions allow you to create custom exceptions for specific needs. Checked exceptions are checked at compile-time & must be handled or declared, while unchecked exceptions are not checked & typically represent programming errors.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.