Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Exceptions in java → Throw in Java

Exceptions in java

Throw in Java

In Java, the throw keyword is used to explicitly throw an exception. This is particularly useful when you want to create custom exceptions or throw an exception based on user-defined conditions.

Concept of throw Keyword

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. The throw keyword is mainly used to throw custom exceptions. The syntax of the Java throw keyword is given below:
throw keyword syntaxthrow instance;
Here, instance must be of type Throwable or a subclass of Throwable. For example, Exception is a subclass of Throwable and user-defined exceptions usually extend the Exception class. Example of throw Keyword Here’s an example of how to use the throw keyword in Java:
Basic example of throw keyword in exception handling using java public class TestThrow1 { // function to check if person is eligible to vote or not public static void validate(int age) { if(age < 18) { // throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } // main method public static void main(String args[]) { // calling the function validate(13); System.out.println("rest of the code..."); } }


Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote
In this example, we have created a method named validate() that accepts an integer as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message "welcome to vote". Remember, proper exception handling can improve a Java application’s robustness and performance capabilities. It’s an essential part of writing a reliable and fault-tolerant Java program.