Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java throws keyword

As we know that there are two types of exception – checked and unchecked. While unchecked exception (Runtime) doesn't get checked during compilation. throws keyword is mainly used for handling checked exception as using throws we can declare multiple exceptions in one go.

The general form of throws keyword is:
return type methodname() throws exception_class_name
{
	//method code
}
Let's see a program for better understanding :

In this example the method "show()" is throwing two checked exceptions so we have declared those exceptions in the method signature using throws Keyword. If we do not declare these exceptions then the program will throw a compilation error.

import java.io.*;
public class ThrowsDemo {
void show(int num)throws IOException, ClassNotFoundException{
	if(num==1)
	throw new IOException("Exception Message1");
	else
	throw new ClassNotFoundException("Exception Message2");
	}
}
class Demo{
	public static void main(String args[]){
		try{
			ThrowsDemo obj=new ThrowsDemo();
			obj.show(1);
		}catch(Exception ex){
			System.out.println(ex);
		}
	}
}

Output

java.io.IOException: Exception Message1


throw vs. throws

let's look the difference between throw and throws which is one of the popular interview question.

throw throws
1) throw keyword is used to explicitly throw an exception. throws keyword is used to declare an exception.
2) Checked exception cannot be propagated. Checked exception can be propagated.
3) throw is followed by an instance. throws is followed by class.
4) throw is used within the method. throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException, SQLException.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext