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

throws

Example

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

public class Main {
  
static void checkAge(int age) throws ArithmeticException {
    
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 throws keyword specifies the type of exception that a method may throw, with various exception types accessible in Java such as ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, and more.

Distinguishing 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.