Error Handling with Exceptions【1】

来源:互联网 发布:linux下查看mysql用户 编辑:程序博客网 时间:2024/06/05 05:04

The basic philosophy of Java is that “badly formed code will not be run.”

Java最基本的哲学是“糟糕的代码不会被执行”。

The ideal time to catch an error is at compile time, before you even try to run the program. However, not all errors can be detected at compile time. The rest of the problems must be handled at run time through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficulty properly.

最良捕获错误信息的时机应该是在编译时,在运行程序之前。但是并非所有的错误信息在此时都可以捕获。而剩余部分代码则必须能够在运行时能够通过某种手段将错误发送到一个可以解决这个难题的程序中。

C and other earlier languages often had multiple error-handling schemes, and these were generally established by convention and not as part of the programming language. Typically, you returned a special value or set a flag, and the recipient was supposed to look at the value or the flag and determine that something was amiss. However, as the years passed, it was discovered that programmers who use a library tend to think of themselves as invincible—as in, “Yes, errors might happen to others, but not in my code.” So, not too surprisingly, they wouldn’t check for the error conditions (and sometimes the error conditions were too silly to check for). If you were thorough enough to check for an error every time you called a method, your code could turn into an unreadable nightmare. Because programmers could still coax systems out of these languages, they were resistant to admitting the truth: that this approach to handling errors was a major limitation to creating large, robust, maintainable programs.

C和一些早期的语言都有几种错误的处理方案,并且这些都是建立在某些约定的基础上的,并不属于程序的一部分。最典型的你返回一个特殊的值或者设置一个标志位,而接受者根据返回值或者标志位再判断出是什么问题。然而这么多年过去了,发现好多的程序员认为自己是无敌的,“错误可能会在别人身上发生,但是在我身上不可能”,所以也不奇怪,它们不检查错误的条件,甚至有时所犯的错误都很愚蠢。如果每次调用一个方法的时候你都花费很多的精力去查找错误,那么你的代码可能也没办法看了。因为程序员们使用这些语言还能凑出一个系统,他们一直拒绝承认这样一个事实“错误的处理已经成为创建巨大,健壮,可维护程序的巨大障碍”。

The solution is to take the casual nature out of error handling and to enforce formality. This actually has a long history, because implementations of exception handling go back to operating systems in the 1960s, and even to BASIC’s “on error goto.” But C++ exception handling was based on Ada, and Java’s is based primarily on C++ (although it looks more like that in Object Pascal).

解决这个问题的办法是“强化错误处理的规范性摒弃错误处理的随意性”。这实际上有很长的历史了,关于异常的处理要追溯到1960年的操作系统中,甚至BASIC语言中的“on error goto”。但是C++的异常处理机制是建立再Ada上的,而Java的处理机制则是主要建立在C++上(尽管看起来更像Object Pascal)。

The word “exception” is meant in the sense of “I take exception to that.” At the point where the problem occurs, you might not know what to do with it, but you do know that you can’t just continue on merrily; you must stop, and somebody, somewhere, must figure out what to do. But you don’t have enough information in the current context to fix the problem. So you hand the problem out to a higher context where someone is qualified to make the proper decision (much like a chain of command).

Exception”这个词的意思本身就是“我对此很反对”。在问题发生的地方你可能不知道应该如何处理,但是你知道这不可能正常的执行下去了;必须停止,而有的地方有时,必须描述出应当如何处理。但是在当前部分你是不知道应该如何处理这个问题,所以你必须把这个问题抛出到更外层的环境中,那里有能力有资格来作出一个完美的决定。

The other rather significant benefit of exceptions is that they clean up error handling code. Instead of checking for a particular error and dealing with it at multiple places in your program, you no longer need to check at the point of the method call (since the exception will guarantee that someone catches it). And, you need to handle the problem in only one place, the so-called exception handler. This saves you code, and it separates the code that describes what you want to do from the code that is executed when things go awry. In general, reading, writing, and debugging code becomes much clearer with exceptions than when using the old way of error handling.

另外一个关于异常处理的重大意义就是它使得错误处理的代码更加有条理性。代替了原来在几个地方判断错误并且处理这个错误,你不需要在方法调用的地方对它进行检查,因为异常机制可以确保在某些地方可以捕获这些。你只需要在一个叫做“异常处理程序”的地方处理这个问题,这样为你节省了代码量,并且将实现部分的代码和错误处理部分的代码分离开来。一般来说,读写代码和异常处理代码都变得比以前更加的清晰。

Because exception handling is the only official way that Java reports errors, and it is enforced by the Java compiler, there are only so many examples that can be written in this book without learning about exception handling. This chapter introduces you to the code you need to write to properly handle exceptions, and the way you can generate your own exceptions if one of your methods gets into trouble.

因为“异常处理程序”是唯一的官方处理Java报出的异常的方法,而且Java编译器对此还有强制性的要求,即使不学习“异常处理程序”在本书中仍还是有很多可写的例子。本章将教会你正确的处理异常信息,当你的方法出现问题的时候如何创建自己的异常类。

Basic exceptions

An exceptional condition is a problem that prevents the continuation of the method or scope that you’re in. It’s important to distinguish an exceptional condition from a normal problem, in which you have enough information in the current context to somehow cope with the difficulty. With an exceptional condition, you cannot continue processing because you don’t have the information necessary to deal with the problem in the current context. All you can do is jump out of the current context and relegate that problem to a higher context. This is what happens when you throw an exception.

异常条件是阻止你的方法正常运行的一个问题,在普通的问题当中分别出这些异常的条件是很重要的,对于普通的问题在当前的环境中你有足够的信息来应付这个难题,但是对于一个异常条件你则无法解决因为在当前的环境中你没有足够的信息来处理这个问题。你所能作的只能是跳出这个环境,将问题提交给更高层的环境中去,这就是当你抛出月个异常后所发生的事情。

Division is a simple example. If you’re about to divide by zero, it’s worth checking for that condition. But what does it mean that the denominator is zero? Maybe you know, in the context of the problem you’re trying to solve in that particular method, how to deal with a zero denominator. But if it’s an unexpected value, you can’t deal with it and so must throw an exception rather than continuing along that execution path.

除法是个很简单的例子,如果你想除以0,这是很值得要检查的条件,但是怎么才知道分母是0呢?你可能知道,在该问题的当前环境中要尽力去解决这个方法,如何处理分母为0的情况。但是如果那是一个不确定的值,你不能那么作,所以抛出一个异常信息要比继续沿着异常的路走要好得多。

When you throw an exception, several things happen. First, the exception object is created in the same way that any Java object is created: on the heap, with new. Then the current path of execution (the one you couldn’t continue) is stopped and the reference for the exception object is ejected from the current context. At this point the exception handling mechanism takes over and begins to look for an appropriate place to continue executing the program. This appropriate place is the exception handler, whose job is to recover from the problem so the program can either try another tack or just continue.

当你抛出一个异常的时候发生了很多的事情:首先,Exception的对象像Java的其它对象一样在堆中创建,这样当前执行的这条路就停止了,因为这条路执行不下去了,异常对象被弹出了当前的环境。而“异常处理程序”机制则开始寻找合适的位置处理继续执行程序。而合适的处理位置则是“异常处理程序”,它的职责就是恢复这个错误,使得程序继续沿着另外一条路继续执行。

As a simple example of throwing an exception, consider an object reference called t. It’s possible that you might be passed a reference that hasn’t been initialized, so you might want to check before trying to call a method using that object reference. You can send information about the error into a larger context by creating an object representing your information and “throwing” it out of your current context. This is called throwing an exception. Here’s what it looks like:

将一个叫做t的对象作为抛出异常的一个小例子。你可能会传递一个没有被初始化的对象,所以你可能再使用这个对象之前要先检查。你可以创建一个描述这个错误的对象,并将这个错误抛出到当前环境之外的环境,这就被称为“抛出一个异常”。就像下面这个例子:

if(t == null)
  throw new NullPointerException();

This throws the exception, which allows you—in the current context—to abdicate responsibility for thinking about the issue further. It’s just magically handled somewhere else. Precisely where will be shown shortly.

这就抛出了一个异常,允许你-在当前环境中-不用在考虑还会发生什么。其它程序会来处理它,它也是我们马上要看到的。

Exception arguments

Like any object in Java, you always create exceptions on the heap using new, which allocates storage and calls a constructor. There are two constructors in all standard exceptions; The first is the default constructor, and the second takes a string argument so you can place pertinent information in the exception:

就像Java的其它对象一样,你也需要使用newheap中创建一个异常的对象,它也分配内存并且调用构造方法。在标准的异常类中有两个构造方法;第一是默认的构造方法,第二个是有一个string参数的,这个参数你可以传递关于异常信息的正确描述:

  throw new NullPointerException("t = null");

This string can later be extracted using various methods, as you’ll see.

你将会看到这个字符串可以被多种方法提取出来。

 
原创粉丝点击