代码执行预料不到的情况,或出错的可能性很大时,使用try-catch语句

  1. 构造一个文件输入流(上传文件时,线上环境的内存情况不确定)出错的可能性很大

  2. 文件上传写入, 数据库事务的提交,还有摄像头和打印机的使用

  3. 使用数据库事务的时候使用try-catch,如果事务执行成功就提交事务,如果事务执行失败就由catch提示错误并回滚事务。还有就是在使用curl方式访问其他网络地址的时候会用到,如果网络访问出错或者网络访问超时就在catch中抛出错误。还有就是之前写winfrom软件的时候调用摄像头和打印机,会使用try-catch。

  4. 程序调用其他人写的程序接口的时候,不敢保证别人的接口返回的都是约定好的返回值。所以如果接口返回约定好的返回值,那么try中的程序正常执行,如果意料之外catch抛出错误。

Return codes are more verbose

 if(doSomething())
 {
    if(doSomethingElse())
    {
       if(doSomethingElseAgain())
      {
           // etc.
      }
       else
      {
          // react to failure of doSomethingElseAgain
      }
    }
    else
    {
       // react to failure of doSomethingElse
    }
 }
 else
 {
    // react to failure of doSomething
 }

This code could well be translated into:

 try
 {
    doSomething() ;
    doSomethingElse() ;
    doSomethingElseAgain() ;
 }
 catch(const SomethingException & e)
 {
    // react to failure of doSomething
 }
 catch(const SomethingElseException & e)
 {
    // react to failure of doSomethingElse
 }
 catch(const SomethingElseAgainException & e)
 {
    // react to failure of doSomethingElseAgain
 }

With the above examples, assume than someone forgets to handle its possible error. The error is ignored when "returned", and will possibly explode later. The same problem won't happen with exception

Return codes are not a universal solution

Return Codes means you can't chain expressions

Exception are typed

You can send different classes for each kind of exception.

Don't ever use catch(...) without rethrowing

The solution could be mixing of return code and exceptions

The solution is to throw when something should not happen. And when something can happen, then use a return code or a parameter to enable to user to react to it

So, the only question is "what is something that should not happen?"

It depends on the contract of your function

Conclusion

When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough

When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen"

But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible".

什么时候需要使用try-catch的更多相关文章

  1. SQLServer如何添加try catch

    在.net中我们经常用到try catch.不过在sqlserver中我们也可以使用try catch捕捉错误,在这里把语法记录下来和大家分享一下, --构建存储过程CREATE PROCEDURE ...

  2. try...catch..finally

    try..catch..finally try{ 代码块1 }catch(Exception e){ 代码块2 }finally{ 代码块3 } catch是抓取代码块1中的异常 代码块2是出异常后的 ...

  3. C++异常处理:try,catch,throw,finally的用法

    写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...

  4. POJ 3278 Catch That Cow(bfs)

    传送门 Catch That Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 80273   Accepted: 25 ...

  5. [c#基础]关于try...catch最常见的笔试题

    引言 在翻看之前总结的常见面试题中,关于try...catch异常处理的还是蛮多了,今天看到这个面试题,也就重新学习一下. try..catch语法 try-catch语句由一个try块后跟一个或多个 ...

  6. 高程(4):执行环境、作用域、上下文执行过程、垃圾收集、try...catch...

    高程三 4.2.4.3 一.执行环境 1.全局执行环境是最外层的执行环境. 2.每个函数都有自己的执行环境,执行函数时,函数环境就会被推入一个当前环境栈中,执行完毕,栈将其环境弹出,把控制器返回给之前 ...

  7. try catch里面try catch嵌套

    try catch里能否内嵌try catch?答案是肯定的.但是等内层try catch出异常之后是个什么执行顺序呢?看下面代码 static void Main(string[] args) { ...

  8. 基础知识《十》java 异常捕捉 ( try catch finally ) 你真的掌握了吗?

    本文转载自  java 异常捕捉 ( try catch finally ) 你真的掌握了吗? 前言:java 中的异常处理机制你真的理解了吗?掌握了吗?catch 体里遇到 return 是怎么处理 ...

  9. java try(){}catch(){}自动资源释放

    从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Manag ...

  10. Java throws Exception、try、catch

    throws Exception是方法后面接的 意思是向上级抛出异常 try{}里面的异常会被外面的catch捕捉到 抛出异常是throw new Exception("异常"); ...

随机推荐

  1. Spring系列之类型转换-12

    目录 类型转换 转换器 SPI 使用`ConverterFactory` 使用`GenericConverter` `ConversionService` 配置一个`ConversionService ...

  2. lgb文档学习

    1.L1和l2损失是什么意思? 相较于MSE,MAE有个优点,那就是MAE对离群值不那么敏感,可以更好地拟合线性,因为MAE计算的是误差y−f(x)的绝对值,对于任意大小的差值,其惩罚都是固定的. 2 ...

  3. CSS 常用样式-盒模型属性

    盒模型又叫框模型,包含了五个用来描述盒子位置.尺寸的属性,分别是宽度 width.高度 height.内边距 padding. 边框 border.外边距 margin. 常见盒模型区域: • 盒模型 ...

  4. VUE项目中检测网页滑动注意事项

    一.this.$nextTick(function () {             window.addEventListener('scroll', this.onScroll, true)   ...

  5. 对表单input输入框加特殊符号(正斜杠和反斜杠)校验

    <p>图片名称:</p><input type="text" name="afterName" style="heigh ...

  6. DHCP分配IP的流程

    1.DHCP客户端以广播的形式发送DHCP Discover报文 2.所有的DHCP服务端都可以接收到这个DHCP Discover报文,所有的DHCP服务端都会给出响应,向DCHP客户端发送一个DH ...

  7. density plot

    FIN=read.table("/Users/zhongyuantian/macshare/workSpace2021/1.TFY/1.3.TFY20201215/1.3.1.TFY1C_T ...

  8. 《Unix/Linux系统编程》第十一周学习笔记

    <Unix/Linux系统编程>第十一周学习笔记 TCP/IP协议 TCP/IP 是互联网的基础.TCP代表传输控制协议.IP代表互联网协议.目前有两个版本的IP,即IPv4和IPv6.I ...

  9. Adams:导出动画

    1 首先模型在adams里能正常运动,点击start simulation仿真一遍. 2 然后在界面上按F8进入Plotting界面. 3 在左上角把Plotting换成Animation. 4 然后 ...

  10. 01.html大致主体格式

    <!DOCTYPE html> 不是HTML标签,就是文档声明标签 告诉浏览器使用哪种html版本来显示网页,其必须在文档中的最前面位置,要放在<html>标签之前, < ...