How is the Java throws clause written?

Source: Internet
Author: User
Tags java throws

If a method can cause an exception but does not handle it, it must specify this behavior so that the callers of the method can protect themselves without exception. Do that. You can include a throws clause in a method declaration. A throws clause lists all the exception types that a method might throw. This is necessary for all exceptions of type except 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 a common form of a method declaration that contains a throws clause:
Type Method-name (parameter-list) throws exception-list{
Body of method
}

Over hereexception-listIs the list of exceptions that the method can throw with a comma-separated exception.

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 the fact, the program will not compile.
This program 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 the program, you need to change two places. First, declare Throwone () to throw a Illegalaccess exception exception. Second, main () must define a Try/catch statement to catch the exception. The correct examples are as follows:
This was 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 an example of the output:
Inside Throwone
Caught Java.lang.IllegalAccessException:demo

How is the Java throws clause written?

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.