Introduction

Throw and throws are keywords in Java. They are used in exception handling in Java. The main difference between them is that throws is used to declare exceptions while throw is used to throw the exception in Java. There are two type of exceptions in Java, checked exceptions and unchecked exceptions.

Throw

The following describes throw statement in Java:
Syntax
public void example()
{
Statements...
if (anythingFalse)
{
throw exception...
}
}
Example
  1. package demo;
  2. import java.io.*;
  3. public class Demo {
  4. static void allow(int marks) {
  5. if (marks < 40) {
  6. throw new ArithmeticException("fail..not allowed");
  7. } else {
  8. System.out.println("allowed");
  9. }
  10. }
  11. public static void main(String[] args) {
  12. allow(35);
  13. }
  14. }
Output
throw in java.jpg

Throws

The following describes the throws clause in Java:
Syntax
void MethodName() throws ExceptionName
{
Statements...
}
Example
  1. package demo;
  2. import java.io.*;
  3. public class Demo {
  4. void checkout() throws IOException {
  5. System.out.println("checking machine");
  6. }
  7. public static void main(String[] args) throws IOException {
  8. Demo check = new Demo();
  9. check.checkout();
  10. System.out.println("successfully checked");
  11. }
  12. }
Output
throws in java.jpg

Example of throw and throws together:

  1. package demo;
  2. import java.io.*;
  3. public class Demo {
  4. void first() throws IOException {
  5. throw new IOException("error");
  6. }
  7. void second() throws IOException {
  8. first();
  9. }
  10. void third() {
  11. try {
  12. second();
  13. } catch (Exception e) {
  14. System.out.println("work is done");
  15. }
  16. }
  17. public static void main(String[] args) {
  18. Demo obj = new Demo();
  19. obj.third();
  20. System.out.println("all in control");
  21. }
  22. }
Output
throw and throws.jpg

Summary

This article has explained the throw statement and the throws clause in Java. These keywords are very important in exception handling in Java.