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:

package com.codingnous.tutorial;


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 = != -1) {
			// Print ASCII value of char.
			System.out.print((char) i);

Exception in thread "main" D:\SampleInput.txt (The system cannot find the file specified) at java.base/ Method) at java.base/ at java.base/ at java.base/ at com.codingnous.tutorial.ThrowsDemo.main(

Throw Example:

package com.codingnous.tutorial;

import java.util.Scanner;

public class ThrowDemo {

	public static void main(String[] args) {

		Scanner s = new Scanner(;
		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));


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(