Creating Exceptions
Deslize para mostrar o menu
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.
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
ExceptionorRuntimeException, 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
1234567public class CustomCheckedException extends Exception { public CustomCheckedException(String message) { super(message); } // Additional constructors can be added if needed }
Example of a Custom Unchecked Exception:
CustomUncheckedException.java
1234567public class CustomUncheckedException extends RuntimeException { public CustomUncheckedException(String message) { super(message); } // Additional constructors can be added if needed }
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.
This exception will be unchecked because such an error violates the program's logic.
public class PurchaseProhibitedException extends RuntimeException {
public PurchaseProhibitedException(String message) {
super(message);
}
}
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354package com.example; public class Main { public static void main(String[] args) { User bob = new User("bob@bobmail.com", "Bob", "some properties..", 20); InternetShopService shopService = new InternetShopService(); shopService.order(bob, "Tequila", 21); } } class InternetShopService { public boolean checkAge(User user, int requiredAge) { return user.getAge() >= requiredAge; } public void order(User user, String item, int requiredAge) { boolean permission = checkAge(user, requiredAge); if (permission) { System.out.println("Ordered successfully!"); } else { throw new PurchaseProhibitedException( String.format("You can't buy %s till you reach %d years old", item, requiredAge)); } //database operations } // other methods } class User { private String email; private String name; private String properties; private int age; public User(String email, String name, String properties, int age) { this.email = email; this.name = name; this.properties = properties; this.age = age; } public int getAge() { return age; } } class PurchaseProhibitedException extends RuntimeException { public PurchaseProhibitedException(String message) { super(message); } }
This code snippet represents a simple model of an online shopping service. It includes classes to manage user details, perform age checks for purchases, and handle a specific type of runtime exception related to purchase restrictions. Here's a step-by-step explanation of what each part of the code does:
Class: User
Purpose: Represents a user of the internet shop.
Attributes:
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.
Constructor:
- Initializes a
Userobject with provided email, name, properties, and age.
Method - getAge:
- Returns the age of the user.
Class: InternetShopService
Purpose: Provides services related to the internet shop, such as age verification and ordering items.
Method - checkAge:
- Takes a
Userobject and an integerrequiredAge. - Returns
trueif the user's age is greater than or equal torequiredAge,falseotherwise.
Method - order:
- Allows a
Userto order an item if they meet therequiredAge. - First, it checks the user's age using the
checkAgemethod. - If checkAge returns true (user is old enough), it prints "Ordered successfully!".
- If
checkAgereturnsfalse, it throws aPurchaseProhibitedExceptionwith 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
Purpose: A custom exception class extending RuntimeException.
Constructor:
- Takes a string
messageand 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758package com.example; public class Main { public static void main(String[] args) { User bob = new User("bob@bobmail.com", "Bob", "some properties..", 20); InternetShopService shopService = new InternetShopService(); try { shopService.order(bob, "Tequila", 21); } catch (PurchaseProhibitedException e) { System.out.println("Exception caught: " + e.getMessage()); } } } class InternetShopService { public boolean checkAge(User user, int requiredAge) { return user.getAge() >= requiredAge; } public void order(User user, String item, int requiredAge) { boolean permission = checkAge(user, requiredAge); if (permission) { System.out.println("Ordered successfully!"); } else { throw new PurchaseProhibitedException( String.format("You can't buy %s till you reach %d years old", item, requiredAge)); } //database operations } // other methods } class User { private String email; private String name; private String properties; private int age; public User(String email, String name, String properties, int age) { this.email = email; this.name = name; this.properties = properties; this.age = age; } public int getAge() { return age; } } class PurchaseProhibitedException extends RuntimeException { public PurchaseProhibitedException(String message) { super(message); } }
Now you can create your own custom exceptions and throw them in your code. Excellent!
1. What are the two main types of exceptions in Java?
2. When creating a custom checked exception, which class should it extend?
3. What is a key characteristic of unchecked exceptions in Java?
4. In the provided example, what is the purpose of the PurchaseProhibitedException class?
5. What does the super(message) call in the constructor of PurchaseProhibitedException do?
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo