Explain the use of the throw and throws clauses in Java programming

  • 2020-04-01 04:12:47
  • OfStack

Java throw: the throwing of an exception
A program can throw an explicit exception with a throw statement. The usual form of a Throw statement is as follows:


 throw ThrowableInstance;


Here, ThrowableInstance must be an object of the Throwable class type or of the Throwable subtype. Simple types, such as int or char, and non-throwable classes, such as String or Object, cannot be used as exceptions. There are two ways to get a Throwable object: using an argument in the catch clause or creating it with the new operator.

Program execution stops immediately after the throw statement; Any subsequent statements are not executed. The most tightly enclosed try block checks to see if it contains a catch statement that matches the exception type. If a matching block is found, control turns to the statement. If nothing is found, the subenclosing try block is checked, and so on. If no catch block is found, the default exception handler interrupts program execution and prints the stack trace.

Here is an example program that creates and throws an exception, and the handler that matches the exception throws it to the outer handler.


// Demonstrate throw.
class ThrowDemo {
 static void demoproc() {
  try {
   throw new NullPointerException("demo");
  } catch(NullPointerException e) {
   System.out.println("Caught inside demoproc.");
   throw e; // rethrow the exception
  }
 }

 public static void main(String args[]) {
  try {
   demoproc();
  } catch(NullPointerException e) {
   System.out.println("Recaught: " + e);
  }
 }
}

The program has two chances to handle the same error. First, main () sets up an exception relationship and then calls demoproc(). The demoproc() method then sets up another exception-handling relationship and immediately throws a new NullPointerException instance, which is caught on the next line. The exception is then thrown again. Here is the output:


Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

The program also explains how to create a standard exception object in Java, with special attention to the following line:


 throw new NullPointerException("demo");


Here, new is used to construct a NullPointerException instance. All Java's built-in runtime exceptions have two constructors: one with no arguments and one with a string argument. When the second form is used, the argument specifies a string that describes the exception. The string is displayed if the object is used as an argument to print() or println(). This can also be done by calling getMessage(), which is defined by Throwable.

Java throws clause
If a method can cause an exception but not handle it, it must specify this behavior so that method callers can protect themselves from exceptions. To do this you can include a throws clause in the method declaration. A throws clause lists all the types of exceptions that a method can throw. This is necessary for all exceptions of types other than Error or RuntimeException and their subclasses. All other types of exceptions that a method can throw must be declared in the throws clause. Failure to do so will result in a compilation error.

The following is the common form of a method declaration that contains a throws clause:


type method-name(parameter-list) throws exception-list{
 // body of method
}

Here, exception-list is a comma-separated list of exceptions that the method can throw.

The following is an incorrect example. The example attempts to throw an exception that it cannot catch. Because the program does not specify a throws clause to declare this fact, the program will not compile.


// This program contains an error and will not compile.
class ThrowsDemo {
 static void throwOne() {
  System.out.println("Inside throwOne.");
  throw new IllegalAccessException("demo");
 }
 public static void main(String args[]) {
  throwOne();
 }
}

To compile the program, you need to change two things. First, you need to declare that throwOne() throws an IllegalAccess Exception. Second, main() must define a try/catch statement to catch the exception. The correct example is as follows:


// This is now correct.
class ThrowsDemo {
 static void throwOne() throws IllegalAccessException {
  System.out.println("Inside throwOne.");
  throw new IllegalAccessException("demo");
 }
 public static void main(String args[]) {
  try {
   throwOne();
  } catch (IllegalAccessException e) {
   System.out.println("Caught " + e);
  }
 }
}

The following is the output of the example:


inside throwOne
caught java.lang.IllegalAccessException: demo


Related articles: