C#学习记录(5):ChatGPT老师指导我学习try-catch

我每天学《C# 小黄书》,边看边练,现在已经学到了67页,感觉进步还可以,还算稳。

今天看到到书里的这段内容,不是很明白:

When an exception is thrown the run time system, which is managing the execution of your program inside the computer, will look for the enclosing catch clause. If your program does not contain a catch for the exception it will be caught by a catch which is part of the run time system. The code in this catch clause will display the exception details and then stop the program. Programs can have multiple levels of try – catch, and the program will use the catch which matches the level of the code in the try block.

于是,我就直接甩给ChatGPT,让它帮我解释,简单来说:

try:这里放置的代码,是我认为有可能出错的。

catch:这里的代码是,如果上面的代码出错了,那么,应该执行这里的代码。

问题是,catch是可以省略不写的。

所以,如果程序员没有写catch,那么,系统会用默认的方式报告错在哪里,并终止程序。

而且,try...catch,也是可以嵌套的哦

感觉ChatGPT挺有意思的点是,它还给我做一个类比——用现实生活做类比,加深我的理解:

现实生活中的“try...catch”

假如,我在上课,突然肚子疼(==发生了异常):

——如果,我身上带了药(==这个药,就是我自己写的catch),我就自行处理;

——如果,我没有带药,但教室有医药箱(==程序有更外层的catch),我也可以用医药箱里的药处理一下;

——如果,上面的药都没有,老师只好叫救护车(==系统终止程序)

看吧,这个类比,一下子就明了了。所以,有了ChatGPT就等于有了一个老师,每年花1800+请一个老师,多便宜啊~~

由于是自学,那么,很重要的一点是,要分清主线是什么,免得过分钻入细节的小路之后,忘了学习的主要路径。针对try-catch,我问ChatGPT:

try-catch这个知识点常用吗?如果常用,在哪些场合会经常用到呢?try-catch的多层嵌套常用吗?

它的回复:

挺常用的,一般在:

——用户输入

——文件读写

——网络请求

对于式层嵌套的场景,不是很常用。但在大型项目中必不可少。

所以,对于初学c#来说,对于try...catch的学习,学到这里就已经够了。

这就避免了自己把时间、精力用到研究try...catch的细节中去了。

原文链接:,转发请注明来源!