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.

Author

Recent Posts

Apple is developing a doorbell camera equipped with Face ID technology.

Apple is reportedly developing a new smart doorbell camera with Face ID technology to unlock…

13 hours ago

Google Launches Its Own ‘Reasoning’ AI Model to Compete with OpenAI

This month has been packed for Google as it ramps up efforts to outshine OpenAI…

3 days ago

You can now use your phone line to call ChatGPT when cellular data is unavailable.

OpenAI has been rolling out a series of exciting updates and features for ChatGPT, and…

4 days ago

Phishers use fake Google Calendar invites to target victims

A financially motivated phishing campaign has targeted around 300 organizations, with over 4,000 spoofed emails…

5 days ago

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

6 days ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

1 week ago