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

Costly Linux Mistakes Beginners Make

1. Running Everything as Root One of the biggest beginner errors. Many new users log…

15 hours ago

How Keyloggers Work

A keylogger is a type of surveillance software or hardware that records every keystroke made…

7 days ago

JavaScript Memoization

In JavaScript, it’s commonly used for: Recursive functions (like Fibonacci) Heavy calculations Repeated API/data processing…

1 month ago

CSS Container Queries: Responsive Design That Actually Makes Sense

For years, responsive design has depended almost entirely on media queries. We ask questions like: “If…

1 month ago

Cron Jobs & Task Scheduling

1. What is Task Scheduling? Task scheduling is the process of automatically running commands, scripts,…

1 month ago

Differences Between a Website and a Web App

Here’s a comprehensive, clear differentiation between a Website and a Web App, from purpose all the…

1 month ago