❮ Previous Next ❯

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{
throw new IOException("Exception Message1");
throw new ClassNotFoundException("Exception Message2");
class Demo{
public static void main(String args[]){
ThrowsDemo obj=new ThrowsDemo();
}catch(Exception ex){

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.

❮ Previous Next ❯


Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Email: info@silantechnology.com
      Phone: 0674-2361252
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved