为什么java到处都要用到try catch?
天蓬老师
天蓬老师 2017-04-18 10:26:06
0
18
1817

新手学java,在什么情况下要包括try catch啊?
我理解的try catch 是处理异常。
难道java有些方法对象 本身就要配合try catch来使用的吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(18)
左手右手慢动作

Because it’s bloated...
Just kidding

黄舟

Java’s design philosophy, Checked Exception. Once a function throws a non-runtime exception, the outside caller must perform a try catch to ensure that all designed exceptions are caught and handled. But there is potential for abuse.

PHPzhong

Can you globally capture exceptions when the program is running?

小葫芦

2333, Basically high-level programming languages ​​have TRY CATCH. Even if they don’t, you still have to think of adding error handling to increase the robustness of the program. Of course, if you and the user don’t care about exceptions at all, you don’t have to write it. You can also write only in more critical positions. Sometimes it is necessary to add transaction processing.

左手右手慢动作

From a current perspective, try/catch is a bit cumbersome, especially when using the underlying JDBC (although this is rarely the case now. When making some informal small adjustments to the database, introducing ORM is a good idea. a less advisable approach). There are try/catch everywhere. And they are all unified SQLException. You have to check the code returned by the underlying layer to know what the problem is.

But this is a feature of java that is all-encompassing. In a larger project, there will often be uncontrollable situations, and it is unlikely that everything will go as planned. Everything goes as you expect. A robust and complete system should have the basis to deal with some unexpected and simple problems. This is the original intention of the Java exception system. In fact, Java allows extended exception definitions for the convenience of development and debugging.

Before spring appeared, when I was building the architecture for the development team, I would introduce custom exceptions in the business layer and database layer to allow team members to expand on their own, but they needed to share and communicate to deal with possible early developments in the business system. circumstances not taken into account. Later this model was well received by maintainers. Because 80-90% of the exceptions that occur in the system are within our custom exception range, runtimeexceptions rarely occur. It is very convenient to find problems and maintain them.

Peter_Zhu

If there is no try, an exception will cause the program to crash. And try can ensure the normal operation of the program, for example:

try{
int i = 1/0;
}catch(Exception e){
........
}

In a calculation, if the divisor is 0, an error will be reported. If there is no try, the program will crash directly. Using try, you can let the program run and output why the error occurred. Try catch, used in conjunction with log4j, will be of great help to the future maintenance of the program.

刘奇

问:新手学java,在什么情况下要包括try catch啊?

Answer: Popularize some basic knowledge:

  • Abnormal principle mechanism

When an exception is thrown in the program, the program jumps out from the code that caused the exception in the program. The Java virtual machine detects and looks for the catch block that handles the exception that matches the try keyword. If found, control is handed over to the catch block. code in the try block, and then continue to execute the program. The code where an exception occurs in the try block will not be re-executed. If no catch block is found to handle the exception, after all the finally block code is executed and the uncaughtException method of the ThreadGroup to which the current thread belongs is called, the current thread that encounters the exception is terminated.

  • Abnormal structure

The Throwable class is defined in the Java exception structure, and Exceotion and Error are its two derived subclasses. Exception represents an exception caused by network failure, file damage, device error, illegal user input, etc. Such exceptions can be handled through the Java exception capture mechanism. Error represents an error that occurs in the Java runtime environment, such as: JVM memory overflow, etc.

  • Summary explanation

Exceptions are an instinctive response to program problems. Using try catch means that you can handle exceptions in the corresponding code block well, thereby avoiding abnormal program interruptions. On the contrary, you can throw Exception and throw the exception to the next level.


问:我理解的try catch 是处理异常。难道java有些方法对象 本身就要配合try catch来使用的吗?

Answer: Let’s spread some basic knowledge:

  • Abnormal classification

  • Detectable exceptions: Detectable exceptions are verified by the compiler. For any method that declares to throw an exception, the compiler will enforce processing or declaration rules. If this exception is not caught, the compiler will fail and compilation will not be allowed.

  • Unchecked exception: Unchecked exceptions do not follow processing or declaration rules. When such an exception is raised, no appropriate action is necessarily taken, and the compiler does not check whether such an exception has been resolved.

  • Summary explanation

Regarding this issue, it is recommended to analyze and understand by viewing the relevant source code. The general principle is that as long as the method you call has a detectable exception, you need to handle it. Try catch is one way, or throws Exception. Throw the exception to the next level. The following examples are as follows:

(scenario where try catch is used)

PrintWriter pw = null;
try {
    pw = new PrintWriter(new File(CodeUtil.invoPath, name));
    pw.write(str_invo.toString());
} catch (FileNotFoundException e) {
    throw new RuntimeException(name+"文件未找到!");
}

(View relevant source code analysis)

public PrintWriter(File file) throws FileNotFoundException {
    this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
         false);
}

(Analysis summary)
Because the constructor PrintWriter(File file) is followed by throws FileNotFoundException, you must handle the exception thrown by it when you call the constructor.

阿神

General languages ​​have exception handling mechanisms.

One of my articles provides a brief introduction to Java's exception mechanism. I hope it can help you.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template