Course Content
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
public class CustomCheckedException extends Exception { public CustomCheckedException(String message) { super(message); } // Additional constructors can be added if needed }
Example of a Custom Unchecked Exception:
CustomUncheckedException
public 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
.
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
package 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); } }
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
package 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!
Thanks for your feedback!