Explain how to use throw and throws clauses in Java programming _java

Source: Internet
Author: User
Tags getmessage throwable java throws

Java Throw: Throwing Exceptions
A program can throw a definite 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 Throwable subclass type. A simple type, such as int or char, and a throwable class, such as String or object, cannot be used as an exception. There are two ways to get a Throwable object: Use parameters in a catch clause or create them with the new operator.

The program executes immediately after the throw statement, and any subsequent statements are not executed. The most tightly wrapped try block is used to check whether it contains a catch statement that matches the type of the exception. If a matching block is found, the control shifts to the statement, and if not, the enclosing try block is checked, and so on. If no matching catch block is found, the default exception handler interrupts the execution of the program and prints the stack trajectory.

Here is an example program that creates and throws an exception, and then throws it to the outer handler with an exception-matching 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 opportunities to handle the same error. First, main () sets up an exception relationship and then calls Demoproc (). The Demoproc () method then establishes another exception handling relationship and immediately throws a new NullPointerException instance, NullPointerException is captured on the next line. The exception is then thrown again. The following are the output results:

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

The program also explains how to create Java standard Exception objects, paying special attention to the following line:

 throw New NullPointerException ("demo");


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

Java throws clause
If a method can cause an exception but does not handle it, it must specify this behavior so that the method's callers can protect themselves without exception. To do this you can include a throws clause in the method declaration. A throws clause enumerates all the exception types that a method might throw. This is necessary for all exceptions except for 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 general 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. This 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 is contains an error and would 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 this program, you need to change two places. First, you need to declare throwone () to throw a Illegalaccess exception 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.