简体   繁体   English

避免由于线程生成异常而终止应用程序

[英]Avoid the termination of an applicaiton due to an exception generated by a thread

I'm working on a Client - Server application with Java Sockets. 我正在使用Java套接字开发客户端-服务器应用程序。

The client must wait for a response from the server. 客户端必须等待服务器的响应。 When the server receives the client's request, it performs certain tasks to obtain a result that must be passed to the client - but performing these tasks could cause an error. 当服务器接收到客户端的请求时,它执行某些任务以获得必须传递给客户端的结果-但是执行这些任务可能会导致错误。

Is there any way in which when this error occurs the application does not terminate and can continue processing requests? 发生此错误时,有什么方法可以使应用程序不终止并且可以继续处理请求?

package Socket;

import javax.swing.*;

import java.awt.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server  
{
    public static void main(String[] args) 
    {       
        MainWindow application=new MainWindow();

        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         
    }   
}

class MainWindow extends JFrame implements Runnable
{

    public MainWindow()
    {       
        setBounds(1200,300,280,350);                

        JPanel myPanel= new JPanel();

        myPanel.setLayout(new BorderLayout());

        text=new JTextArea();

        myPanel.add(text,BorderLayout.CENTER);

        add(myPanel);

        setVisible(true);

        Thread t= new Thread(this);

        t.start();      
    }

    private JTextArea text;

    @Override
    public void run() 
    {
        try 
        {
            ServerSocket Server = new ServerSocket(9999);

            while(true)
            {
                Socket mySocket = Server.accept();

                DataInputStream input_stream = new DataInputStream(mySocket.getInputStream());

                String message  = input_stream.readUTF();

                someMethod();           //This method can generate an exception, then the application closes and I can not receive new requests

                text.append("\n" + message);

                mySocket.close();
            }                        
        } 
        catch (IOException ex) 
        {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Catch the exception inside the loop. 在循环内捕获异常。

ServerSocket Server = new ServerSocket(9999);

while(true) {
   try {
       Socket mySocket = Server.accept();
       DataInputStream input_stream = new DataInputStream(mySocket.getInputStream());
       String message  = input_stream.readUTF();

       someMethod();           //This method can generate an exception, then the application closes and I can not receive new requests
       text.append("\n" + message);
       mySocket.close();
   } catch (IOException ex) {
        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
   }
}                        

Then you'll log the exception and just carry on. 然后,您将记录异常并继续进行。

PS: There are probably some exceptions that mean that retries are futile and you need to abandon the process rather than fill the log with a zillion severe errors. PS:可能有一些例外,这意味着重试是徒劳的,您需要放弃该过程,而不是在日志中填充成千上万的严重错误。

I recommend reading the documentation and devising a slightly more mature error handling strategy than 'ignore everything and soldier on'. 我建议阅读文档,并设计一种稍微成熟得多的错误处理策略,而不是“忽略一切并继续前进”。

A try-catch does not have to go around all your code at once. try-catch不必一次遍历所有代码。 The one you have around your whole run method is very useful to log errors that are truly fatal. 您在整个run方法中拥有的方法对于记录真正致命的错误非常有用。 You can have another one around someMethod(); 您可以在someMethod();周围添加另一个someMethod(); to prevent those exceptions from breaking the loop: 为了防止这些异常破坏循环:

try {
    someMethod();
} catch(ZeroDivisionException e) {
    // handle the exception
} catch(SomeOtherException e) {
    // handle the other exception
}

The exceptions here are made up, but I'm sure you get the idea. 这里的例外情况已被弥补,但是我敢肯定,您会明白的。 How you handle them is up to you. 您如何处理它们取决于您。 As long as you don't re-throw any of them, the loop won't end and your outer block won't be triggered. 只要您不重新抛出任何一个,循环就不会结束并且您的外部块也不会被触发。

You can nest catch blocks pretty much however you like, so you can catch IOException in the inner block as well as the outer one. 您可以随意嵌套捕获块,因此可以在内部块和外部块中捕获IOException The outer block will still clean up for the errors you can't control. 外部块仍将清除您无法控制的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM