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


 

目录
相关文章
|
8天前
|
Java
在 Java 中捕获和处理自定义异常的代码示例
本文提供了一个 Java 代码示例,展示了如何捕获和处理自定义异常。通过创建自定义异常类并使用 try-catch 语句,可以更灵活地处理程序中的错误情况。
|
8天前
|
Java
在 Java 中,如何自定义`NumberFormatException`异常
在Java中,自定义`NumberFormatException`异常可以通过继承`IllegalArgumentException`类并重写其构造方法来实现。自定义异常类可以添加额外的错误信息或行为,以便更精确地处理特定的数字格式转换错误。
|
9天前
|
IDE 前端开发 Java
怎样避免 Java 中的 NoSuchFieldError 异常
在Java中避免NoSuchFieldError异常的关键在于确保类路径下没有不同版本的类文件冲突,避免反射时使用不存在的字段,以及确保所有依赖库版本兼容。编译和运行时使用的类版本应保持一致。
|
10天前
|
Java 编译器
如何避免在 Java 中出现 NoSuchElementException 异常
在Java中,`NoSuchElementException`通常发生在使用迭代器、枚举或流等遍历集合时,尝试访问不存在的元素。为了避免该异常,可以在访问前检查是否有下一个元素(如使用`hasNext()`方法),或者使用`Optional`类处理可能为空的情况。正确管理集合边界和条件判断是关键。
|
13天前
|
Java
Java异常捕捉处理和错误处理
Java异常捕捉处理和错误处理
14 1
|
15天前
|
Java 编译器 开发者
Java异常处理的最佳实践,涵盖理解异常类体系、选择合适的异常类型、提供详细异常信息、合理使用try-catch和finally语句、使用try-with-resources、记录异常信息等方面
本文探讨了Java异常处理的最佳实践,涵盖理解异常类体系、选择合适的异常类型、提供详细异常信息、合理使用try-catch和finally语句、使用try-with-resources、记录异常信息等方面,帮助开发者提高代码质量和程序的健壮性。
33 2
|
22天前
|
Java
如何在 Java 中处理“Broken Pipe”异常
在Java中处理“Broken Pipe”异常,通常发生在网络通信中,如Socket编程时。该异常表示写入操作的另一端已关闭连接。解决方法包括:检查网络连接、设置超时、使用try-catch捕获异常并进行重试或关闭资源。
|
24天前
|
存储 安全 Java
如何避免 Java 中的“ArrayStoreException”异常
在Java中,ArrayStoreException异常通常发生在尝试将不兼容的对象存储到泛型数组中时。为了避免这种异常,确保在操作数组时遵循以下几点:1. 使用泛型确保类型安全;2. 避免生类型(raw types)的使用;3. 在添加元素前进行类型检查。通过这些方法,可以有效防止 ArrayStoreException 的发生。
|
26天前
|
人工智能 Oracle Java
解决 Java 打印日志吞异常堆栈的问题
前几天有同学找我查一个空指针问题,Java 打印日志时,异常堆栈信息被吞了,导致定位不到出问题的地方。
33 2
|
29天前
|
Java 索引
如何避免在 Java 中引发`StringIndexOutOfBoundsException`异常
在Java中,处理字符串时若访问了不存在的索引,会抛出`StringIndexOutOfBoundsException`异常。为避免此异常,应确保索引值在有效范围内,例如使用`length()`方法检查字符串长度,并确保索引值不小于0且不大于字符串长度减1。
下一篇
无影云桌面