Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

throw

Example

If the age is below 18, throw an exception displaying “Access denied”. If the age is 18 or older, print “Access granted”.

public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }
 
  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}

Definition and Usage

The throw keyword facilitates the creation of custom errors.

It is employed alongside an exception type, with various exception types accessible in Java such as ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, and more.

This exception type is frequently utilized in conjunction with a custom method, as illustrated in the example above.

Differences between throw and throws:

throw

throws

employed to raise an exception within a method

It’s used to specify the type of exception that a method may throw.

It’s not possible to throw multiple exceptions.

It’s possible to declare multiple exceptions.

Syntax

  •            The throw keyword is succeeded by an object instantiation (of a specified type).
  •            Employed within a method.

Syntax

  •           The throws keyword is succeeded by a class.
  •           And incorporated into the method signature.