Throwing Exceptions

Handling Exceptions

Throwing Exceptions

🙋 Need help? Ask an expert now!

We examined scenarios where our own code throws errors and are familiar with the exceptions that are generally defined in Java. But have you thought about possible reasons you would want to create your own exceptions? Why, you ask?

For example, when users are utilizing your program and entering data into it, for instance their name, if they enter numbers or symbols into a name field, would you want that user to get an error specifically for that field in your program letting them know they must use characters? This is why programmers in Java are able to throw exceptions with error messages that are specific to their individual programs. Let's see an example below.
package exlcode;

public class ThrowingExceptionsExample {

  public static int exampleVariableOne = 1;
  public static int exampleVariableTwo = 12;

  public static void main(String[] args){
    add(exampleVariableOne, exampleVariableTwo);

  public static void add(int exampleVariableOne, int exampleVariableTwo) throws ArithmeticException, NumberFormatException {
    // creates a new ArithmeticException condition where
    // exampleVariableOne and exampleVariableTwo cannot be 0
    if (exampleVariableOne == 0 || exampleVariableTwo == 0) {
      throw new ArithmeticException("One of the exampleVariables are 0");
    } else {
      System.out.println("The sum of the two numbers: " + (exampleVariableOne + exampleVariableTwo));

The program above throws the "ArithmeticException" if one of the parameters are zero as adding nothing defeats the purpose of using the add() method. The exception can either be handled with a catch{} block or thrown to the user as an exception error.

When you have one exception you need to throw, use the following syntax, throw new ExceptionName(description), where "ExceptionName" has to match one of the exceptions that are already defined in Java. If you are throwing two or more exceptions, you can use the word throws in the method header and list out the exception names with commas separating them. The program above is an example of how you can throw exceptions in the method header.

Edit Me on GitHub!

Application Question

Which of these Java reserved words is used to explicitly specify the exceptions that a particular method might throw?