Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Creating Exceptions | Exceptions
Java JUnit Library. Types of Testing
course content

Course Content

Java JUnit Library. Types of Testing

Java JUnit Library. Types of Testing

1. Testing in Development
2. Unit Tests
3. Exceptions

bookCreating 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:

  1. Define a New Class: Your exception class should extend either Exception or RuntimeException, depending on whether you want it to be a checked or unchecked exception;
  2. 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:

java

CustomCheckedException

copy
1234567
public class CustomCheckedException extends Exception { public CustomCheckedException(String message) { super(message); } // Additional constructors can be added if needed }

Example of a Custom Unchecked Exception:

java

CustomUncheckedException

copy
1234567
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.

java

main

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
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.

java

main

copy
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
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!

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?
What are the two main types of exceptions in Java?

What are the two main types of exceptions in Java?

Select the correct answer

When creating a custom checked exception, which class should it extend?

When creating a custom checked exception, which class should it extend?

Select the correct answer

What is a key characteristic of unchecked exceptions in Java?

What is a key characteristic of unchecked exceptions in Java?

Select the correct answer

In the provided example, what is the purpose of the `PurchaseProhibitedException` class?

In the provided example, what is the purpose of the PurchaseProhibitedException class?

Select the correct answer

What does the `super(message)` call in the constructor of `PurchaseProhibitedException` do?

What does the super(message) call in the constructor of PurchaseProhibitedException do?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt