代码执行预料不到的情况,或出错的可能性很大时,使用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. char和int的类型转换

    char类型是16位的,底层采用unicode编码保存.char类型是可以直接赋值给int类型的,因为是16位到32位低到高.举个例子比如int i='1';打印i的值是49.char类型跟int类型 ...

  2. PVE联网及更换国内源

    一.PVE联网 第一次安装PVE,正常情况下PVE的IP是在我们上网的网段的.没有网络有可能是没有配置DNS服务器地址或DNS地址是软路由网关地址.解决方法有3种: 1:设置DHCP自动获取网络地址和 ...

  3. 20181224蒋嘉豪-exp5

    网络对抗技术Exp5 信息搜集与漏洞扫描20181224jjh 目录 网络对抗技术Exp5 信息搜集与漏洞扫描20181224jjh 信息搜集技术与隐私保护--知识点总结 间接收集 直接收集 社会工程 ...

  4. CSS vw与vh动态设置元素的高度宽度

    做为一个前端开发者,总有一天我们要设置页面某一部分内容自适应浏览器窗口大小,下面分享下使用vw和vh的设置方式, 一波解释: v(即viewport):可视窗口,也就是浏览器窗口大小.vw Viewp ...

  5. windows 获取USB,发现安卓设备,转载自www.jb51.net/article/164456.htm

    转载 作者:jgw2008 import win32com.client def CheckDev(): wmi = win32com.client.GetObject ("winmgmts ...

  6. Django 基础(二)

    cookie和session from django.shortcuts import render from django.http import HttpResponse # Create you ...

  7. winIO介绍

    WinIO程序库允许在32位的Windows应用程序中直接对I/O端口和物理内存进行存取操作.通过使用一种内核模式的设备驱动器和其它几种底层编程技巧,它绕过了Windows系统的保护机制. 因为需要加 ...

  8. git push错误failed to push some refs to的解决

    问题说明 当我们在github版本库中发现一个问题后,你在github上对它进行了在线的修改:或者你直接在github上的某个库中添加readme文件或者其他什么文件,但是没有对本地库进行同步.这个时 ...

  9. 9.Java的LinkedList/Deque相关方法

    Java的LinkedList/Deque中add/offer/push,remove/pop/poll的区别 它们来自不同的接口 add/remove源自集合,所以添加到队尾,从队头删除: offe ...

  10. 2.javaweb-begin

    1.回顾前端知识 1.CSS 1) CSS的角色:页面显示的美观风格 2) CSS的基础语法:标签样式:类样式:ID样式:组合样式:嵌入式样式表:内部样式表:外部样式表 3) 盒子模型:border. ...