Creating Exceptions
It's time to move on to creating your own custom exceptions that you can throw in your programs. First, it's important to note that there are two types of exceptions.
Types of Exceptions in Java
- Checked Exceptions: These are exceptions that must be either caught or declared in the method signature. They are checked at compile-time.
Example:IOException
; - Unchecked Exceptions: These exceptions are not checked at compile time. They usually indicate programming errors, such as logic mistakes or incorrect API usage.
Example:NullPointerException
.
Note
You may have noticed that up to this point, we've been discussing unchecked exceptions because they affect the logic of the application. In this chapter, we'll also be using unchecked exceptions, which signify errors in the logic of a method/application.
Creating Custom Exceptions
To create a custom exception in Java, you typically extend either Exception
( for checked exceptions ) or RuntimeException
( for unchecked exceptions ).
Steps to Create a Custom Exception:
- Define a New Class: Your exception class should extend either
Exception
orRuntimeException
, depending on whether you want it to be a checked or unchecked exception; - Constructor Overloading: Define constructors for your exception class. You can create multiple constructors to pass different types of information about the exception ( e.g., a simple message or another throwable cause ).
Example of a Custom Checked Exception:
CustomCheckedException.java
Example of a Custom Unchecked Exception:
CustomUncheckedException.java
Practice
Now, let's practice a bit and create our own exception, which will be used when the user is not of the required age to buy something in an online store. This exception should have a name that represents the error it indicates.
For example, NotOfLegalAgeException
or PurchaseProhibitedException
.
Note
This exception will be unchecked because such an error violates the program's logic.
Now, we can use this exception in our code and throw it in methods. Let's write a method that checks the user's age and throws an exception if they are younger than 21 years old.
main.java
Code Description
Class: User
email
: A string storing the user's email.-
name
: A string storing the user's name.-
properties
: A string to store additional properties of the user.-
age
: An integer representing the user's age.User
object with provided email, name, properties, and age.getAge
: Class: InternetShopService
checkAge
:User
object and an integer requiredAge
.- Returns
true
if the user's age is greater than or equal to requiredAge
, false
otherwise.order
:User
to order an item
if they meet the requiredAge
.- First, it checks the user's age using the
checkAge
method.- If
checkAge
returns true
(user is old enough), it prints "Ordered successfully!".- If
checkAge
returns false
, it throws a PurchaseProhibitedException
with a message indicating that the user cannot buy the item until they reach the required age.- There's a comment indicating a place for database operations, presumably for processing the order.
Class: PurchaseProhibitedException
RuntimeException
.message
and passes it to the superclass (RuntimeException
) constructor. This message typically contains details about why the exception is thrown (e.g., user not being old enough to make the purchase).
As you can see, we're using the exception we created inside the code. Now, all that's left is to handle this exception when the method that throws it is called and print the exception message to the console. We will do this, of course, using a try-catch
structure.
main.java
Now you can create your own custom exceptions and throw them in your code. Excellent!
Tudo estava claro?
Conteúdo do Curso
Java JUnit Library. Types of Testing
Java JUnit Library. Types of Testing
Creating Exceptions
It's time to move on to creating your own custom exceptions that you can throw in your programs. First, it's important to note that there are two types of exceptions.
Types of Exceptions in Java
- Checked Exceptions: These are exceptions that must be either caught or declared in the method signature. They are checked at compile-time.
Example:IOException
; - Unchecked Exceptions: These exceptions are not checked at compile time. They usually indicate programming errors, such as logic mistakes or incorrect API usage.
Example:NullPointerException
.
Note
You may have noticed that up to this point, we've been discussing unchecked exceptions because they affect the logic of the application. In this chapter, we'll also be using unchecked exceptions, which signify errors in the logic of a method/application.
Creating Custom Exceptions
To create a custom exception in Java, you typically extend either Exception
( for checked exceptions ) or RuntimeException
( for unchecked exceptions ).
Steps to Create a Custom Exception:
- Define a New Class: Your exception class should extend either
Exception
orRuntimeException
, depending on whether you want it to be a checked or unchecked exception; - Constructor Overloading: Define constructors for your exception class. You can create multiple constructors to pass different types of information about the exception ( e.g., a simple message or another throwable cause ).
Example of a Custom Checked Exception:
CustomCheckedException.java
Example of a Custom Unchecked Exception:
CustomUncheckedException.java
Practice
Now, let's practice a bit and create our own exception, which will be used when the user is not of the required age to buy something in an online store. This exception should have a name that represents the error it indicates.
For example, NotOfLegalAgeException
or PurchaseProhibitedException
.
Note
This exception will be unchecked because such an error violates the program's logic.
Now, we can use this exception in our code and throw it in methods. Let's write a method that checks the user's age and throws an exception if they are younger than 21 years old.
main.java
Code Description
Class: User
email
: A string storing the user's email.-
name
: A string storing the user's name.-
properties
: A string to store additional properties of the user.-
age
: An integer representing the user's age.User
object with provided email, name, properties, and age.getAge
: Class: InternetShopService
checkAge
:User
object and an integer requiredAge
.- Returns
true
if the user's age is greater than or equal to requiredAge
, false
otherwise.order
:User
to order an item
if they meet the requiredAge
.- First, it checks the user's age using the
checkAge
method.- If
checkAge
returns true
(user is old enough), it prints "Ordered successfully!".- If
checkAge
returns false
, it throws a PurchaseProhibitedException
with a message indicating that the user cannot buy the item until they reach the required age.- There's a comment indicating a place for database operations, presumably for processing the order.
Class: PurchaseProhibitedException
RuntimeException
.message
and passes it to the superclass (RuntimeException
) constructor. This message typically contains details about why the exception is thrown (e.g., user not being old enough to make the purchase).
As you can see, we're using the exception we created inside the code. Now, all that's left is to handle this exception when the method that throws it is called and print the exception message to the console. We will do this, of course, using a try-catch
structure.
main.java
Now you can create your own custom exceptions and throw them in your code. Excellent!
Tudo estava claro?