When do you need to use try...catch in a java program?

In Java programs, sometimes it is necessary to "surround" the code with try...catch. The core purpose of using try is to catch possible exceptions in the program and then throw them, rather than directly terminating the run with an error.

First, here is the basic syntax of try..catch..finally

try { 
    程序无异常时执行的代码块 
} catch { 
    程序异常时执行的代码块:一般写需要抛出的异常类型和名称 
} finally { 
    不论是否异常都要执行代码块 
}

Then in the following scenarios, you will need to use try..catch to capture program exceptions

  • When the program involves opening and closing resources such as data files and closing them after use, try-catch should be used to prevent io exceptions;
  • When it comes to network connection programming, due to the uncertainty of network connections, it is necessary to try...catch the relevant code blocks to prevent program errors caused by network exceptions;
  • There are also some unpredictable code blocks that may cause errors that require try..catch; such as: i/0 exceptions, null pointer exceptions, array out-of-bounds exceptions, etc.

Guess you like

Origin blog.csdn.net/zhangkai__/article/details/133046992