Java 'throw' Keyword Tutorial

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exceptions.

Usage

The throw keyword is mainly used to throw custom exceptions.

throw new ArithmeticException("Person is not eligible to vote");

Example

public class TestThrow {
   static void validate(int age) {
     if(age < 18)
        throw new ArithmeticException("not valid");
     else
        System.out.println("welcome to vote");
   }
   
   public static void main(String args[]) {
      validate(13);
      System.out.println("rest of the code...");
  }
}

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.