Use Exceptions Rather Than Return Codes

  Back in the distant past there were many languages that didn't have exceptions.In those languages the techniques for handling and reportiing errors were limited.You either set an error flag or returned an error code that caller could check.The problem with these approaches is that they clutter the caller.The caller must check for errors immediately after the call.Unfortunately, it's easy to forget.For this reason it is better to throw an exception when you encounter an error.

Write your Try-Catch-Finally Statement First

  One of the most insteresting things about exceptions is that they define a scope within your program.When you execute code in the try portion of a try-catch-finally statement,you are stating that execution can abort at any point and then resume at the catch.In a way, try blocks are like transactions.Your catch has to leave your program in a consistent state,no matter what happens in the try.For this reason it is good practice to start with a try-catch-finally statement when you are writting code that could throw exception.This helps you define what the user of that code should expect,no matter what goes wrong with the code that is executed in the try.

  Try to write tests that force exceptions,and then add behavior to your handler to satisfy your tests.This will cause you to build the transaction scope of the try block first and will help you maintain the transaction nature of that scope.

Use Unchecked Exceptions

  We have to decide-really-whether checked exceptions are worth their price.The price of checked exceptions is an Open/Closed Principle violation.If you throw a checked exception from a method in your code and the catch is three levels above, you must declare that exception in the signature of each method between you and the catch.This means that a change at a low level of the software can force signature changes on many higher levels.The change modules must be rebuilt and redeployed even though nothing they care about change.

  Checked exceptions can sometimes be useful if you are writing a critical library: You must catche them.But in general application development the dependency costs outweight the benefits.

Provide Context with Exceptions

  Each exception that you throw should provide enough context to determine the source and location of an error.In Java, you can get a stack trace from any exception;however, a stack trace can't tell you the intent of the operation that failed.

  Create information error messages and pass them along with your exceptions.Mention the operation that failed and the type of failture.If you are logging in your application, pass along enough information to be able to log the error in your catch.

Define Exception Classes in Terms of a Caller's Needs

  There are many ways to classify errors.We can classify them by their source:Did they come from one component or another?Or their type:Are they device failures,network failures, or programming errors?However, when we define exception classes in an application,our most important concern should be how they are caught.

  Wrappers can be very useful.In fact, wrapping third-party APIs is a best practice.When you wrap a third-party API,you minimize your dependencies upon it:You can choose to move to a different library in the future without much penalty.Wrapping also makes it easier to mock out third-party calls when you are testing your own code.

  One final advantage of wrapping is that you aren't tired to a particular vendor's API design choices.You can define an API that you fell comfortable with.Often a single exception class is fine for a particular area of code.The information sent with the exception can distinguish the errors.Use different classes only if there are times when you want to catch one exception and allow the other one to pass through.

Define the Normal Flow

  If you follow the advice in the preceding sections, you'll end up with a good amount of separation between your business logic and your error handling.The bulk of your code will start to look like a clean unadorned algorithm.However,the process of doing this pushes error detection to the edges of your program.You wrap external APIs so that you can throw your own exceptions, and you define a handler above your code so that you can deal with any aborted computation.Most of the time this is a great approach,but there are some times when you may not want to abort.

  Sometimes you create a class or configure an object so that it handles a special case for you.When you do, the client code doesn't have to deal with exceptional behavior.That behavior is encapsulated in the special case object.

Don't Return Null

  I think that any discussion about error handling should include mention of the things we do that invite errors.The first on the list is returning null.I can't begin to count the number of applications I've seen in which nearly every other line was a check for null.

  When we return null, we are essentially creating work for ourselves and foisting problems upon our callers.All it takes is one missing null check to send an application spinning out of control.

Don't Pass Null

  Returning null from methods is bad,but passing null into methods is worse.Unless you are working with an API wichi expects you to pass null,you shoud aviod passing null in your code whenever possible.

  In most programming languages there is no good way to deal with a null that is passed by a caller accidentally.Because this is the case,the rational approach is to forbid passing null by default.When you do, you can code with the knowledge taht a null in an argument list is an indication of a problem, and end up with far fewer careless mistakes.

Error Handling的更多相关文章

  1. Erlang error handling

    Erlang error handling Contents Preface try-catch Process link Erlang-way error handling OTP supervis ...

  2. MySQL Error Handling in Stored Procedures 2

    Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered ...

  3. setjmp()、longjmp() Linux Exception Handling/Error Handling、no-local goto

    目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...

  4. Error Handling and Exception

    The default error handling in PHP is very simple.An error message with filename, line number and a m ...

  5. Clean Code–Chapter 7 Error Handling

    Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...

  6. [RxJS] Error handling operator: catch

    Most of the common RxJS operators are about transformation, combination or filtering, but this lesso ...

  7. MySQL Error Handling in Stored Procedures---转载

    This tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in store ...

  8. Error Handling in ASP.NET Core

    Error Handling in ASP.NET Core 前言  在程序中,经常需要处理比如 404,500 ,502等错误,如果直接返回错误的调用堆栈的具体信息,显然大部分的用户看到是一脸懵逼的 ...

  9. beam 的异常处理 Error Handling Elements in Apache Beam Pipelines

    Error Handling Elements in Apache Beam Pipelines Vallery LanceyFollow Mar 15 I have noticed a defici ...

随机推荐

  1. js广告弹窗

    生活中我们经常遇到一些烦人的广告页面,比方说弹窗,悬浮等等各种广告.有的同事甚至都下一个屏蔽广告插件到浏览器上.这样就防止了广告的干扰. 但是我们学前端的必须是要知道广告弹窗这个做的过程,甚至是它的原 ...

  2. Android跨进程通信的四种方式

    由于android系统中应用程序之间不能共享内存.因此,在不同应用程序之间交互数据(跨进程通讯)就稍微麻烦一些.在android SDK中提供了4种用于跨进程通讯的方式.这4种方式正好对应于andro ...

  3. php : 获取对象的属性名

    方案有多种: 一. 使用 get_object_vars() 方法 缺点: 只能显示 public 的 //只显示public的 var_dump(get_object_vars($test)); 处 ...

  4. 深入浅出设计模式——中介者模式(Mediator Pattern)

    模式动机 在用户与用户直接聊天的设计方案中,用户对象之间存在很强的关联性,将导致系统出现如下问题: 系统结构复杂:对象之间存在大量的相互关联和调用,若有一个对象发生变化,则需要跟踪和该对象关联的其他 ...

  5. socket初级使用(客户端)

    在国庆这段时间里用零星的一些时间看了一下socket的学习资料,由于笔者偏向学习实用方面的内容,因此此篇文章涉及理论知识较少,主要是以实现思路(怎么做)为主,但在实现之前还是需要了解一些基础的理论知识 ...

  6. STM32学习笔记(九) 外部中断,待机模式和事件唤醒

    学会知识只需要不段的积累和提高,但是如何将知识系统的讲解出来就需要深入的认知和系统的了解.外部中断和事件学习难度并不高,不过涉及到STM32的电源控制部分,还是值得认真了解的,在本文中我将以实际代码为 ...

  7. Error: Cannot find a valid baseurl for repo: base

    解决方法如下(修改dns配置) vi /etc/resolv.conf 在此文件最后加入:nameserver 8.8.8.8 如果没有vi编辑器可用: echo "nameserver 8 ...

  8. spring+mybatis

    ---恢复内容开始--- 使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地 ...

  9. git diff patch

    如何生成patch:修改一个地方,然后git diff > xxx.patch 就会生成一个patch文件,这里的关键似乎是, 源文件的某个模块的版本要和线上发布的最新版本要一致,这样patch ...

  10. java 滤镜实现

    一句话,滤镜的实现就是对像素点(RGBA)进行再运算,输出新的像素点.    F(r,g,b,a)=G(r,g,b,a); 这个公式包含四个变换,即RGB颜色空间中RGB三个分量的变换以及透明度Alh ...