throws Keyword Overview

throws : - it is used to specify the exception that can be thrown from a method.

Syntax :-

Modifier return_type methodname(type parameter) throws exception;

e.g: -

public static void parseInt(String no) throws NumberFoundException;
As we can see, throwing an exception is easy if one of the existing exception classes works for us. In this case:

  1. Find an appropriate exception class.

  2. Make an object of that class.

  3. Throw it.

Once a method throws an exception, the method does not return to its caller. This means that we do not have to worry about cooking up a default return value or an error code.
public class Divide { public static void main(String s[]) { try { displayDivision(100,0); } catch(ArithmeticException e) { System.out.println("main() exception "+e); } } public static void displayDivision(int a,int b) throws ArithmeticException { int c=a/b; } }


C:\JavaProgram>java Divide
main() exception java.lang.ArithmeticException: / by zero

Download this example


Latest Tutorial

Most Visited Tutorial