How to Throw Exceptions

Before catching an exception it is must to be thrown first. This means that there should be a code somewhere in the program that could catch the exception.

How to Throw Exceptions

Before catching an exception it is must to be thrown first. This means that there should be a code somewhere in the program that could catch the exception.

How to Throw Exceptions

How to Throw Exceptions in Java

     

Before catching an exception it is must to be thrown first. This means that there should be a code somewhere in the program that could catch the exception. We use throw statement to throw an exception or simply use the throw keyword with an object reference to throw an exception. A single argument is required by the throw statement i.e. a throwable object. As mentioned earlier Throwable objects are instances of any subclass of the Throwable class. 

throw new VeryFastException();

Note: The reference should be of type Throwable or one of its subclasses.

For instance the example below shows how to throw an exception. Here we are trying to divide a number by zero so we have thrown an exception here as "throw new MyException("can't be divided by zero");"

class MyException extends Exception {
public MyException(String msg){
super(msg);
}
}

public class Test {

static int  divide(int first,int second) throws MyException{ 
  if(second==0) 
  throw new MyException("can't be divided by zero");
return first/second;
 }

 public static void main(String[] args) {
  try {
System.out.println(divide(4,0));
  }
catch (MyException exc) {
exc.printStackTrace();
  }
  }
}

Output of program:

C:\Roseindia\vinod\Exception>javac Test.java

C:\Roseindia\vinod\Exception>java Test
MyException: can't be divided by zero
at Test.divide(Test.java:10)
at Test.main(Test.java:15)

C:\Roseindia\vinod\Exception>

Download this example

Difference between throw and throws keywords

Whenever we want to force an exception then we use throw keyword. the throw keyword (note the singular form) is used to force an exception. It can also pass a custom message to your exception handling module. Moreover throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. For instance in the above example we have used - 

throw new MyException ("can't be divided by zero");

Whereas when we know that a particular exception may be thrown or to pass a possible exception then we use throws keyword. Point to note here is that the Java compiler very well knows about the exceptions thrown by some methods so it insists us to handle them. We can also use throws clause on the surrounding method instead of try and catch exception handler. For instance in the above given program we have used the following clause which will pass the error up to the next level -

static int  divide(int first,int second) throws MyException{