No announcement
 

Throws & Throw Keywords

If we does not handle a checked exception inside a method then the method must declare it using the throws keyword. We can throw an exception using the throw keyword.

Throws Example:

ThrowsDemo.java

package com.codingnous.tutorial;

import java.io.FileInputStream;
import java.io.IOException;

public class ThrowsDemo {

	// Throws exception.
	public static void main(String[] args) throws IOException {

		// The below file may not exist hence it can throw an exception.
		// But we didn't surround the code in try..catch, hence throws keyword used in
		// method signature.
		FileInputStream fi = new FileInputStream("D:\\SampleInput.txt");

		int i;

		// Read char value one by one until no char is left.
		while ((i = fi.read()) != -1) {
			// Print ASCII value of char.
			System.out.print((char) i);
		}
	}
}

Output
Exception in thread "main" java.io.FileNotFoundException: D:\SampleInput.txt (The system cannot find the file specified) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:216) at java.base/java.io.FileInputStream.(FileInputStream.java:157) at java.base/java.io.FileInputStream.(FileInputStream.java:111) at com.codingnous.tutorial.ThrowsDemo.main(ThrowsDemo.java:14)

Throw Example:

ThrowDemo.java

package com.codingnous.tutorial;

import java.util.Scanner;

public class ThrowDemo {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);
		System.out.print("Enter number to compute square of: ");
		int num = s.nextInt();

		// Assuming our squaring operation does not accept negative numbers.
		if (num < 0) {
			throw new ArithmeticException("Negative number not permissible for squaring.");
		} else {
			System.out.println("Square is " + (num * num));
		}
	}

}

Output
Enter number to compute square of: -5 Exception in thread "main" java.lang.ArithmeticException: Negative number not permissible for squaring. at com.codingnous.tutorial.ThrowDemo.main(ThrowDemo.java:15)