Java throws clause

If a method can result in an exception but does not handle it, it must specify this behavior so that the caller of the method can protect themselves without an exception occurs. You can do this include a throws clause in the method declaration. A throws clause lists all the types of exceptions a method may throw. This is in addition to or Error RuntimeException subclasses thereof and all types of abnormalities are needed. All other types of exceptions a method can throw must be declared in the throws clause. Failure to do so will result in a compiler error.

The following is the general form of the method declaration comprising a throws clause:
type-name Method (Parameter-List) throws Exception {-List
// body of Method
}

Here, exception-list is thrown in the method may have abnormal comma-separated list.

Here is an incorrect example. This example attempts to throw an exception that it can not capture. Because the program does not specify a throws clause to declare the fact that the program will not compile.
This error AN Program the contains // Will Not and the compile.
Class {ThrowsDemo
static void throwOne () {
System.out.println ( "Inside throwOne.");
The throw new new IllegalAccessException ( "Demo");
}
public static void main (String args []) {
throwOne ();
}
}

To compile the program, you need to be changed in two places. First, the need to declare throwOne () caused IllegalAccess Exception exception. Second, main () must be defined a try / catch statement to catch this exception. Correct the following example:
// This IS now correct.
Class {ThrowsDemo
static void throwOne () throws IllegalAccessException {
System.out.println; ( "Inside throwOne.")
The throw new new IllegalAccessException ( "Demo");
}
public static void main (String args []) {
the try {
throwOne ();
} the catch (IllegalAccessException E) {
System.out.println ( "Caught" + E);
}
}
}

The following are examples of output results:
Inside throwOne
Caught java.lang.IllegalAccessException: Demo

VII. Multithreaded programming
1. The concept of threads
2. the Java threading model
3. The main thread
4. Create a thread
5. Create a multithreaded
6. Use isAlive () and join () of
7. thread priority
8. thread synchronization
9. communication between the threads
10. a thread deadlock
11. the thread suspend, resume and terminate

Guess you like

Origin blog.csdn.net/Javaxuxuexi/article/details/92428346