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

10 Signs That Show You’re a Great Developer

Becoming a great developer involves more than just writing impeccable code; it requires a blend…

1 hour ago

How YouTube’s Monetization Policy Works

In recent years, YouTube has become not only a platform for entertainment but also a…

1 day ago

JavaScript skills you need for React

JavaScript serves as the backbone of modern web development, and its proficiency is vital for…

2 days ago

How Facebook’s Monetization Policy Really Works

In the digital age, social media platforms have become more than just places to connect…

3 days ago

Mastering Event Handling in JavaScript: A Comprehensive Guide

Introduction: Events play a pivotal role in modern web development, enabling developers to create interactive…

6 days ago

Embracing Flat Design: A Guide to Modern UI Aesthetics

Introduction: In the realm of user interface (UI) design, flat design principles have emerged as…

1 week ago