Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Creating Exceptions | Exceptions
course content

Contenido del Curso

Java JUnit Library. Types of Testing

Creating ExceptionsCreating 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.java

Example of a Custom Unchecked Exception:

java

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.

java

main.java

Code Description
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 User object 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 User object and an integer requiredAge.
    - Returns true if the user's age is greater than or equal to requiredAge, false otherwise.
  • Method - order:
  • - Allows a 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


  • Purpose: A custom exception class extending RuntimeException.
  • Constructor:
  • - Takes a string 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.

    java

    main.java

    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?

    Selecciona la respuesta correcta

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

    Selecciona la respuesta correcta

    What is a key characteristic of unchecked exceptions in Java?

    Selecciona la respuesta correcta

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

    Selecciona la respuesta correcta

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

    Selecciona la respuesta correcta

    ¿Todo estuvo claro?

    Sección 3. Capítulo 5
    course content

    Contenido del Curso

    Java JUnit Library. Types of Testing

    Creating ExceptionsCreating 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.java

    Example of a Custom Unchecked Exception:

    java

    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.

    java

    main.java

    Code Description
    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 User object 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 User object and an integer requiredAge.
    - Returns true if the user's age is greater than or equal to requiredAge, false otherwise.
  • Method - order:
  • - Allows a 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


  • Purpose: A custom exception class extending RuntimeException.
  • Constructor:
  • - Takes a string 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.

    java

    main.java

    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?

    Selecciona la respuesta correcta

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

    Selecciona la respuesta correcta

    What is a key characteristic of unchecked exceptions in Java?

    Selecciona la respuesta correcta

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

    Selecciona la respuesta correcta

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

    Selecciona la respuesta correcta

    ¿Todo estuvo claro?

    Sección 3. Capítulo 5
    some-alt