Master java skills

Throw Keyword

Throw and throws are two more keywords which are parts of java exception handling mechanism. Let’s understand their usage.

throw keyword

So far, we have seen exceptions being thrown in our programs automatically, meaning by JVM. But exceptions can also be thrown explicitly (in our programs). throw keywords is given for that. Using throw keyword, we can throw exceptions programatically.

We can throw checked as well as unchecked exceptions using throw keyword.

What is the need of throwing exceptions explicitly

Sometimes, we may not want to handle an exception in the method it occurs; rather we want it to be handled by the callers of that method. In such situations, we may either throw the same exception or a custom exception from that method using throw keyword.

syntax :

throw new Exception ("My custom exeption");

throw new IOException ("IO exception");

Example – throw unchecked exception

In the below example, we are programatically throwing ArithmeticException, instead of handling it.

package com.javatrainingschool;

public class ThrowKeywordExample {

	public static void main (String [] args) {
		System.out.println("Result of division = " + divideTwoNums(40, 0));
	}
	
	public static int divideTwoNums(int a, int b) {
	    if(b == 0) {
	    	throw new ArithmeticException("Divisor cannot be zero.");
	    }
		int result = a/b;
		return result;
	}
}
Output :
Exception in thread "main" java.lang.ArithmeticException: Divisor cannot be zero.
	at com.javatrainingschool.NestedTryExample.divideTwoNums(NestedTryExample.java:11)
	at com.javatrainingschool.NestedTryExample.main(NestedTryExample.java:6)

Note -> If we throw an unchecked exception from a method, it is optional for the caller method of that method to handle the exception. The caller method may choose to handle the thrown exception or it can simply do nothing about it.

Note -> However, if we throw a checked exception from a method, it is mandatory for the method to add it in the throws clause. It is also mandatory for the caller method to handle the exception. The caller method either has to handle the exception using try-catch block or mention it in the throws clause of the method.

Example – throwing checked exception

package com.javatrainingschool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ThrowKeywordExample {

	public static void main (String [] args) {
		try {
			readFile();
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFoundException caught in main method");
		} catch (IOException e) {
			System.out.println("IOException caught in main method");
		}
	}
	
	public static void readFile() throws FileNotFoundException, IOException {
		
		File file = new File("C:\\Users\\saras\\Desktop\\test.txt");
		try {
			BufferedReader bf = new BufferedReader(new FileReader(file));
			String str = null;
			while((str = bf.readLine()) != null) {
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			System.out.println("Throwing FileNotFoundException from readFile method.");
			throw e;
		} catch (IOException e) {
			System.out.println("Throwing IOException from readFile method.");
			throw e;
		}
	}
	    
}
Output :
Throwing FileNotFoundException from readFile method.
FileNotFoundException caught in main method

Throwing custom exception example

In the below example, we are going to throw a custom exception. For that, we have to create a class that extends Exception or any other class of exception framework.

package com.javatrainingschool;

public class JTSException extends Exception {

	private String msg;

        //toString method
        //getters and setters methods
        //constructors
}
package com.javatrainingschool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class NestedTryExample {

	public static void main (String [] args) {
		try {
			readFile();
		} catch (JTSException e) {
			System.out.println("JTSException caught in main method : " + e.getMsg());
		}
	}
	
	public static void readFile() throws JTSException {
		
		File file = new File("C:\\Users\\saras\\Desktop\\test.txt");
		try {
			BufferedReader bf = new BufferedReader(new FileReader(file));
			String str = null;
			while((str = bf.readLine()) != null) {
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			System.out.println("Throwing custom JTSException from readFile method.");
			throw new JTSException("FileNotFoundException");
		} catch (IOException e) {
			System.out.println("Throwing custom JTSException from readFile method.");
			throw new JTSException("IOException");
		}
	}
	    
}
Output :
Throwing custom JTSException from readFile method.
JTSException caught in main method : FileNotFoundException