java

Throw And Throws Exception in Java

Throw

Throw is a keyword that is used in Java to declare an exception which is similar to the try/catch block. It is used to declare an explicit exception inside a block of code or method.

Example

public class AgeCheck {
 void checkAge(int age) {
  if(age < 18){
   throw new ArithmeticException("Not eligible to vote");
  }else {
   System.out.println("Eligible to vote");
  }
 }

public static void main(String args[]){
//Create an object of the class to access the method
AgeCheck ageCheck = new AgeCheck();
ageCheck.checkAge(13) //Not eligible to vote
}
}

Throws

Throws is a keyword also as well as a method signature used to declare an exception which might be thrown by the method during the program execution.

public class DivisionCheck {
 int divide(int a, int b) throws ArithmeticException {
 int result = a/b;
 return result;
 }
public static void main(String args[]){
//Create an object of the class to access the method
 DivisionCheck divisionCheck = new DivisionCheck();
 try {
  System.out.println(divisionCheck.divide(15,0));
 }catch(ArithmeticException e){
  System.out.println("You cannot divide by zero);
 }
}
}

Throws is usually used to check the process of program execution, especially when you are not sure of the input you might get from the user.

THE END.

Recent Posts

Google Announces that AI-developed Drug will be in Trials by the End of the Year

Isomorphic Labs, a drug discovery start-up launched four years ago and owned by Google’s parent…

5 hours ago

Instagram Extends Reels Duration to 3 Minutes

Regardless of whether TikTok faces a U.S. ban, Instagram is wasting no time positioning itself…

2 days ago

AWS Expands Payment Options for Nigerian Customers, Introducing Naira (NGN) for Local Transactions

Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…

6 days ago

Why JavaScript Remains Dominant in 2025

JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…

1 week ago

Amazon Moves to Upgrade Alexa with Generative AI Technology

Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…

1 week ago

Smuggled Starlink Devices Allegedly Used to Bypass India’s Internet Shutdown

SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…

1 week ago