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

简介:  然而,很多时候,你将希望传达更多的错误信息而不只是一个java.lang中的类。通常这个异常类本身标志遇到这个不正确的情况。例如,如果一个被抛出异常拥有IllegalArgumentException异常。

 然而,很多时候,你将希望传达更多的错误信息而不只是一个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


 

目录
相关文章
|
2月前
|
Java
java自定义Service的异常
java自定义Service的异常
15 0
|
2月前
|
Java
Java中的异常链:从根源到解决方案
Java中的异常链:从根源到解决方案
41 0
|
2月前
|
存储 监控 Java
Java认识异常(超级详细)
Java认识异常(超级详细)
|
3天前
|
存储 Java 开发者
探索Java开发中触发空指针异常的场景
作为一名后端开发者在Java编程的世界中,想必大家对空指针并不陌生,空指针异常是一种常见而又令人头疼的问题,它可能会在我们最不经意的时候突然出现,给我们的代码带来困扰,甚至导致系统的不稳定性,而且最可怕的是有时候不能及时定位到它的具体位置。针对这个问题,我们需要深入了解触发空指针异常的代码场景,并寻找有效的方法来识别和处理这些异常情况,而且我觉得空指针异常是每个Java开发者都可能面临的挑战,但只要我们深入了解它的触发场景,并采取适当的预防和处理措施,我们就能够更好地应对这个问题。那么本文就来分享一下实际开发中一些常见的触发空指针异常的代码场景,并分享如何有效地识别和处理这些异常情况。
17 1
探索Java开发中触发空指针异常的场景
|
4天前
|
SQL 网络协议 Java
Java异常详解
Java异常详解
8 1
|
13天前
|
Java 程序员 编译器
|
15天前
Swagger2异常:java.lang.NumberFormatException: For input string: ““
Swagger2异常:java.lang.NumberFormatException: For input string: ““
20 1
|
16天前
|
存储 Java 程序员
JavaSE&Java的异常
JavaSE&Java的异常
25 0
|
27天前
|
Java 开发者
Java中的受检异常和非受检异常的区别
Java中的受检异常和非受检异常的区别
|
28天前
|
Java
异常之道:探索Java异常处理与日志的黄金准则
异常之道:探索Java异常处理与日志的黄金准则
26 0