Introduction
Using try-catch blocks and exceptions, you can handle failures that occur during runtime. While some methods require explicit exception handling, others can be handled differently.
Creating Methods that Throw Exceptions
Methods that can throw checked exceptions must declare this using the throws
keyword. The following example shows two methods
one that doesn't declare and exception but can still throw a runtime exception. The other method declares a checked exception.
The user of that method needs to handle it.
|
|
When calling a method that throws a checked exception, you'll get a compilation error if you don't handle it:
|
|
Throwing Exceptions inside Constructors
Constructors can throw exceptions, which is useful for validating object during creation. Here's an example that validates a username during object instantiation:
|
|
Basic Exception Handling with Try-Catch
The standard way to handle exceptions in Java is using try-catch blocks. The following example shows you how to use the try statement.
|
|
Handling Specific Exception Types
You can catch different types of exceptions separately. This approach is useful when a method might throw multiple exception types. Here's an implementation where the User constructor could throw both IllegalArgumentException and ValidationException exceptions:
|
|
Combining catch statements
If the exception handling is the same for two or more exceptions you can use a pipe to combine these catch statements. The following example shows you how to improve the previous error handling.
|
|
Using Optional to Avoid using Exceptions
In some cases you can prevent having to use exceptions. For example when looking for a user you could use Optional to know if a user was found or not.
|
|
Using RuntimeExceptions for Unchecked Exceptions
When you want to throw exceptions without forcing the caller to handle them, use RuntimeException. You also don't have to declare them in the signature of the method. So other developers won't immediately know that the method throws an exception. This is how you throw a runtime exception:
|
|