reprint: http://shmilyaw-hotmail-com.iteye.com/blog/1881302Objective
It's been a while to discuss this topic. I remember a few years ago when I went to the interview, someone asked me a similar question. Is the handling of exceptions in Java thread. Because the Java thread itself involves concurrency, locks, and other related issues are complex enough. Plus exception handling these things makes it even more special. To sum up, there are three main problems. 1. Can I throw an exception in Java-initiated line thread? 2. Can I catch an exception on the thread line? 3. If you can catch an exception, for checked exception and unchecked exception, what are their respective ways of handling it?
Now, let's talk about each of them.
Throws an exception in the thread
We can try the online thread throw exception. As we understand it, it is assumed that we want to throw an exception in a method, and we need to add a declaration to the method header of that definition. Then one of the simplest ways might be as follows:
Java code
- public class task < span class= "keyword" >implements runnable {
-
- @Override
- public void run () throws exception {
- int number0 = integer.parseint (
- < span class= "keyword" >throw new exception (
- }
- }
However, if we compile the above code, we will find that it is not compiled at all. The system reported errors are:
Java code
- Task.java:3:error:run () in Task cannot implement run () in Runnable
- public Void Run () throws Exception {
- ^
- Overridden method does not throw Exception
- 1 Error
We find this way unworkable. In other words, it is not possible to directly throw an anomaly online thread. This, however, raises the question of what to do if we do have an exception in the thread code. For example, we use a thread to access some files or IO operations on the network, resulting in an exception. or when accessing certain resources, the system crashes. Such a scenario is really possible, and we need to discuss these situations further.
Several ways to handle exceptions
Some of the previously mentioned thread access resources produced an exception. We can see, for example, when we access the file system, we throw IOException, FileNotFoundException and other exceptions. The code we are accessing actually needs to be dealt with in two ways. One is to increase the throws IOException, FileNotFoundException and other abnormal modifiers in the method of using the modified resources. There is also the addition of the Try/catch section directly in this section of the code block. By the previous discussion we have found that the way to add throws exception in a method declaration is not feasible. Then there's only one way to use Try/catch.
In addition, we also know that in the handling of exceptions, general anomalies can be divided into checked exception and unchecked exception. As unchecked exception, they often refer to serious system errors or system design errors, such as error, OutOfMemoryError, or a system that crashes directly. There is nothing we can do to recover from this anomaly. So how do we deal with this situation?
Checked exception
The thread inside process checked exception, according to our previous understanding, we can directly capture it to deal with. We've seen it in some examples of thread. For example, the following part of the code:
Java code
- Import Java.util.Date;
- Import Java.util.concurrent.TimeUnit;
- Public class Filelock implements Runnable {
- @Override
- public Void Run () {
- For (int i = 0; i < i++) {
- System.out.printf ("%s\n", new Date ());
- try {
- TimeUnit.SECONDS.sleep (1);
- } catch (Interruptedexception e) {
- System.out.printf ("The Fileclock has been interrupted");
- }
- }
- }
- }
We define a thread execution code, and here we need to catch the exception because of the call to the TimeUnit.SECONDS.sleep () method. Because the method itself throws interruptedexception, we have to use the Try/catch block to handle it.
The code we start the thread and interact with it is as follows:
Java code
- Import Java.util.concurrent.TimeUnit;
- Public class Main {
- public static void Main (string[] args) {
- //Creates a Fileclock runnable object and a Thread
- //To run it
- Fileclock clock=New Fileclock ();
- Thread thread=new thread (clock);
- //Starts the Thread
- Thread.Start ();
- try {
- //Waits Five seconds
- TimeUnit.SECONDS.sleep (5);
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- };
- //Interrupts the Thread
- Thread.Interrupt ();
- }
- }
This part of the code is to start the filelock thread and try to break it. We can find that the code executing in the Filelock is able to handle the exception normally when running.
Therefore, in thread, if you want to deal with checked exception, a simple try/catch block can be.
Unchecked exception
For this unchecked exception, it is relatively different. In fact, there is an instance method in the definition of thread: Setuncaughtexceptionhandler (Uncaughtexceptionhandler). This method can be used to deal with some unchecked exception. So, what is the scenario of this scenario?
The Setuncaughtexceptionhandler () method is equivalent to an event registration entry. Inside the JDK, the method is defined as follows:
Java code
- Public void Setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) {
- CheckAccess ();
- Uncaughtexceptionhandler = eh;
- }
While Uncaughtexceptionhandler is an interface, it declares the following:
Java code
- Public interface Uncaughtexceptionhandler {
- /**
- * Method invoked when the given thread terminates due to the
- * Given uncaught exception.
- * <p>any Exception thrown by this method would be ignored by the
- * Java Virtual Machine.
- * @param t the thread
- * @param e The exception
- */
- void Uncaughtexception (Thread t, Throwable e);
- }
When an exception occurs, the Uncaughtexception method of the Uncaughtexceptionhandler parameter that we pass in will be called.
To synthesize the previous discussion, the concrete steps of our side to implement the handle unchecked exception method can be summarized as follows:
1. Define a class to implement the Uncaughtexceptionhandler interface. Contains the logic and steps for exception handling in the implemented method.
2. Define thread execution structure and logic. This step is the same as the normal thread definition.
3. In the method of creating and executing the sub-thread, add a Thread.setuncaughtexceptionhandler statement before the Thread.Start () statement to implement the registration of the processing logic.
Below, let's follow the steps defined here to implement an example:
The first is to implement the Uncaughtexceptionhandler interface section:
Java code
- Import Java.lang.Thread.UncaughtExceptionHandler;
- Public class Exceptionhandler implements Uncaughtexceptionhandler {
- public void Uncaughtexception (Thread t, Throwable e) {
- System.out.printf ("An exception have been captured\n");
- System.out.printf ("Thread:%s\n", T.getid ());
- System.out.printf ("Exception:%s:%s\n",
- E.getclass (). GetName (), E.getmessage ());
- System.out.printf ("Stack Trace: \ n");
- E.printstacktrace (System.out);
- System.out.printf ("Thread Status:%s\n", t.getstate ());
- }
- }
The exception handling logic we add here is simple, just to print out the thread's information and the exception information.
We then define the contents of the thread, where we deliberately let the thread produce a unchecked exception:
Java code
- Public class Task implements Runnable {
- @Override
- public Void Run () {
- int NUMBER0 = Integer.parseint ("TTT");
- }
- }
From this code we can see that the parameters inside the Integer.parseint () are wrong and will definitely throw an exception.
Now, let's fill in the parts that create the thread and register the processing logic:
Java code
- public class main {
- public static void main (string[] args) {
- task task = new task ()
- Thread thread = new thread (Task),
- thread.setuncaughtexceptionhandler (new Exceptionhandler ());
- thread.start () ;
- }
- }
Now we're going to execute the whole program and we'll see the following result:
Java code
- An exception have been captured
- Thread: 8
- Exception:java.lang.NumberFormatException:For input string: "TTT"
- Stack Trace:
- Java.lang.NumberFormatException:For input string: "TTT"
- At Java.lang.NumberFormatException.forInputString (Numberformatexception.java: +)
- At Java.lang.Integer.parseInt (Integer.java:492)
- At Java.lang.Integer.parseInt (Integer.java:527)
- At Task.run (Task.java:5)
- At Java.lang.Thread.run (Thread.java:722)
- Thread status:runnable
This part of the output is just the definition of the Uncaughtexceptionhandler interface we implemented earlier.
Therefore, for unchecked exception, we can also use similar event registration mechanism to do a certain degree of processing.
Summarize
Java thread is a strange part of the exception. You cannot throw an exception directly in a thread. General Online thread Encounter checked exception, recommended practice is to use the Try/catch block to deal with. For unchecked exception, a more reasonable way is to register an object instance that implements the Uncaughtexceptionhandler interface to handle. It is difficult to answer these details if they have not been met.
Handling policies for exceptions in Java thread