java中的异常--Exceptions in Java-- 第二部分

 然而,很多时候,你将希望传达更多的错误信息而不只是一个java.lang中的类。通常这个异常类本身标志遇到这个不正确的情况。例如,如果一个被抛出异常拥有IllegalArgumentException异常。那就标志某些程序通过了一个非法的参数调用了这个方法。有的时候你想要指出一个遇到了非法的条件(这个非法条件没有在java.lang中被定义)的方法。

Other times, however, you will want to convey more information about the abnormal condition than a class from java.lang will allow. Usually, the class of the exception object itself indicates the type of abnormal condition that was encountered. For example, if a thrown exception object has class IllegalArgumentException, that indicates someone passed an illegal argument to a method. Sometimes you will want to indicate that a method encountered an abnormal condition that isn't represented by a class in the Throwable family of java.lang.

 举个例子,假设你正在些一个java程序模拟一个客户虚拟喝咖啡。考虑有可能在喝咖啡的时候发生的异常。图2层次结构展示了一个部分可能性。

As an example, imagine you are writing a Java program that simulates a customer of a virtual café drinking a cup of coffee. Consider the exceptional conditions that might occur while the customer sips. The class hierarchy of exceptions shown in Figure 2 represents a few possibilities.

Figure 2. Exception hierarchy for coffee sipping  喝咖啡异常层次图

如果客户发现咖啡是冷的,他会很不爽,你的程序能抛出TooColdException异常。另一方面,如果客户发现咖啡太热了,你的程序应该能抛出TooHotException异常。这些情况能被认为是异常,因为他们在喝咖啡中不是被希望的情况。(异常情况不是很罕见,仅仅是超出正常情况的事件)你的新异常类可能如下:

If the customer discovers, with dismay, that the coffee is cold, your program could throw a TooColdException. On the other hand, if the customer discovers that the coffee is overly hot, your program could throw a TooHotException. These conditions could be exceptions because they are (hopefully) not the normal situation in your café. (Exceptional conditions are not necessarily rare, just outside the normal flow of events.) The code for your new exception classes might look like this:

 // In Source Packet in file except/ex1/TemperatureException.java
class TemperatureException extends Exception {
}
// In Source Packet in file except/ex1/TooColdException.java
class TooColdException extends TemperatureException {
}
// In Source Packet in file except/ex1/TooHotException.java
class TooHotException extends TemperatureException {
}

这个温度异常类层次图声明了三个新的异常类型提供给你程序。注意每个异常类自己表示这种不正常的温度情况。 TooColdException 说明咖啡比较冷,TooHotException 说明太热。同时也要注意TemperatureException 类扩展自Exception类而不是Throwable、Error或者其他在java.lang中的类。
This family of classes, the TemperatureException family, declares three new types of exceptions for your program to throw. Note that each exception indicates by its class the kind of abnormal condition that would cause it to be thrown: TemperatureException indicates some kind of problem with temperature; TooColdException indicates something was too cold; and TooHotException indicates something was too hot. Note also that TemperatureException extends Exception -- not Throwable, Error, or any other class declared in java.lang.

 

Throwing exceptions 抛出异常

抛出一个异常,你简单使用throw加上一个异常的引用,例如:  throw new TooColdException();引用类型必须是Throwable 或者Throwable 的子类。
To throw an exception, you simply use the throw keyword with an object reference, as in:

                        throw new TooColdException();

The type of the reference must be Throwable or one of its subclasses.

下面代码展示了客户类VirtualPerson抛出异常的例子。如果咖啡没有满足类VirtualPerson里设置的值,就会抛出异常。注意java除了throw还有一个throws 关键字。throw 关键字只能被用来抛出一个异常。throws 关键字将在文章下面讲解。

The following code shows how a class that represents the customer, class VirtualPerson, might throw exceptions if the coffee didn't meet the customer's temperature preferences. Note that Java also has a throws keyword in addition to the throw keyword. Only throw can be used to throw an exception. The meaning of throws will be explained later in this article.

 // In Source Packet in file except/ex1/VirtualPerson.java
class VirtualPerson {
    private static final int tooCold = 65;
    private static final int tooHot = 85;
    public void drinkCoffee(CoffeeCup cup) throws
        TooColdException, TooHotException {
        int temperature = cup.getTemperature();
        if (temperature <= tooCold) {
            throw new TooColdException();
        }
        else if (temperature >= tooHot) {
            throw new TooHotException();
        }
        //...
    }
    //...
}
// In Source Packet in file except/ex1/CoffeeCup.java
class CoffeeCup {
    // 75 degrees Celsius: the best temperature for coffee
    private int temperature = 75;
    public void setTemperature(int val) {
        temperature = val;
    }
    public int getTemperature() {
        return temperature;
    }
    //...
}

                    


Catching exceptions  捕获异常

在java中捕获异常,你写了一个try 带了一个或者多个catch 字句的代码块。每一个catch子句指定一个具体的要被处理的异常类型。try块里面的代码被catch里的异常关联。如果try里的代码抛出一个异常,相关的catch子块将会被java虚拟机调用。如果虚拟机找到一个可以处理的异常,程序就继续执行这个catch块中的代码。
To catch an exception in Java, you write a try block with one or more catch clauses. Each catch clause specifies one exception type that it is prepared to handle. The try block places a fence around a bit of code that is under the watchful eye of the associated catchers. If the bit of code delimited by the try block throws an exception, the associated catch clauses will be examined by the Java virtual machine. If the virtual machine finds a catch clause that is prepared to handle the thrown exception, the program continues execution starting with the first statement of that catch clause.

举个例子,考虑一个需要一个参数的命令行程序,一个string能被解析成一个integer类。当你有一个string并且想要一个int,你能调用Integer 中的parseInt()方法。如果你输入的这个string代表为integer,parseInt() 将会返回相应的值。如果这个sting不能代表一个integer,parseInt()方法就会抛出NumberFormatException异常。下面是实现代码:

As an example, consider a program that requires one argument on the command line, a string that can be parsed into an integer. When you have a String and want an int, you can invoke the parseInt() method of the Integer class. If the string you pass represents an integer, parseInt() will return the value. If the string doesn't represent an integer, parseInt() throws NumberFormatException. Here is how you might parse an int from a command-line argument:

                        // In Source Packet in file except/ex1/Example1.java
class Example1 {
    public static void main(String[] args) {
        int temperature = 0;
        if (args.length > 0) {
            try {
                temperature = Integer.parseInt(args[0]);
            }
            catch(NumberFormatException e) {
                System.out.println(
                    "Must enter integer as first argument.");
                return;
            }
        }
        else {
            System.out.println(
                "Must enter temperature as first argument.");
            return;
        }
        // Create a new coffee cup and set the temperature of
        // its coffee.
        CoffeeCup cup = new CoffeeCup();
        cup.setTemperature(temperature);
        // Create and serve a virtual customer.
        VirtualPerson cust = new VirtualPerson();
        VirtualCafe.serveCustomer(cust, cup);
    }
}

这里,parseInt() 调用包括在一个try块中,try的附加块是catch子句(捕获异常NumberFormatException)

Here, the invocation of parseInt() sits inside a try block. Attached to the try block is a catch clause that catches NumberFormatException:

                        catch(NumberFormatException e) {
    System.out.println(
        "Must enter integer as first argument.");
    return;
}

小写字符e代表了一个抛出异常对象NumberFormatException 的引用。这个引用能在catch块中使用,尽管这个例子他没有被使用。(catch块的例子在文档后面会被使用。
wercase character e is a reference to the thrown (and caught) NumberFormatException object. This reference could have been used inside the catch clause, although in this case it isn't. (Examples of catch clauses that use the reference are shown later in this article.)

如果使用者把Harumph 作为第一个参数给Example1 程序,parseInt() 将会抛出一个NumberFormatException 异常并且catch 块将捕获到这个异常,程序将会输出Continued 。

If the user types Harumph as the first argument to the Example1 program, parseInt() will throw a NumberFormatException exception and the catch clause will catch it. The program will print:   Continued


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值