Java throw and throws

Java Throw and Throws keyword

What is Java throw and Throws? 

  • In Java, throw and throws are keywords used in exception handling.

  • throw is used to explicitly throw an exception from a method or block of code. It is followed by an instance of the Throwable class or one of its subclasses.

  • throws is used in a method signature to declare that the method may throw one or more types of exceptions. This allows callers of the method to handle or propagate the exceptions appropriately.

  • To understand the Java Throw and Throws, Read the Complete Article.

Java Exceptions:

  • In Java, exceptions can be categorized into two types:
    • Checked Exceptions: These are the exceptions that are checked by the compiler at the time of compilation. If a method throws a checked exception, the method must either handle the exception or declare it using the throws keyword. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.
    • Unchecked Exceptions: These are the exceptions that are not checked by the compiler at the time of compilation. These are also known as runtime exceptions. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException
  • It’s important to note that while unchecked exceptions do not have to be declared or handled explicitly, 
Java Throw and Throws

Let’s look at the Java Throw and Throws to perform certain operations.

Example 1: Java Program to Java throws Keyword

Run
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter a number: ");
        String input = reader.readLine();
        int number = Integer.parseInt(input);
        System.out.println("The number is: " + number);
    }
}

Output

Enter a number: 9
The number is: 9

Example 2 : Throwing multiple exceptions

Run
public class Main {
    public static void main(String[] args) {
        int age = -1;
        try {
            setAge(age);
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }
    
    public static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        System.out.println("Age is: " + age);
    }
}

Output

Age cannot be negative

Example 3 : How to use checked exceptions in Java. 

Run

import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            readFile("myfile.txt");
        } catch (IOException ex) {
            System.out.println("An error occurred while reading the file: " + ex.getMessage());
        }
    }
    
    public static void readFile(String fileName) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}

Output

An error occurred while reading the file: myfile.txt (No such file or directory)

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription