Java Error Handling with Exceptions

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

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.

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).

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.

1.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.

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.

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:

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.

2.Catching an exception

If a method throws an exception, it must assume that exception will be “caught” and dealt with. One of the advantages of exception handling is that it allows you to concentrate on the problem you’re trying to solve in one place, and then deal with the errors from that code in another place.

To see how an exception is caught, you must first understand the concept of a guarded region. This is a section of code that might produce exceptions and is followed by the code to handle those exceptions.

(1)The try block

If you’re inside a method and you throw an exception (or another method you call within this method throws an exception), that method will exit in the process of throwing. If you don’t want a throw to exit the method, you can set up a special block within that method to capture the exception. This is called the try block because you “try” your various method calls there. The try block is an ordinary scope preceded by the keyword     try:

try {

// Code that might generate exceptions

}

If you were checking for errors carefully in a programming language that didn’t support exception handling, you’d have to surround every method call with setup and error testing code, even if you call the same method several times. With exception handling, you put everything in a try block and capture all the exceptions in one place. This means your code is much easier to write and read because the goal of the code is not confused with the error checking.

(2)Exception handlers

Of course, the thrown exception must end up someplace. This “place” is the exception handler, and there’s one for every exception type you want to catch. Exception handlers immediately follow the try block and are denoted by the keyword catch:

try {

// Code that might generate exceptions

} catch(Type1 id1) {

// Handle exceptions of Type1

} catch(Type2 id2) {

// Handle exceptions of Type2

} catch(Type3 id3) {

// Handle exceptions of Type3

}

Each catch clause (exception handler) is like a little method that takes one and only one argument of a particular type. The identifier (id1, id2, and so on) can be used inside the handler, just like a method argument. Sometimes you never use the identifier because the type of the exception gives you enough information to deal with the exception, but the identifier must still be there.

Each catch clause (exception handler) is like a little method that takes one and only one argument of a particular type. The identifier (id1, id2, and so on) can be used inside the handler, just like a method argument. Sometimes you never use the identifier because the type of the exception gives you enough information to deal with the exception, but the identifier must still be there.

The handlers must appear directly after the try block. If an exception is thrown, the exception handling mechanism goes hunting for the first handler with an argument that matches the type of the exception. Then it enters that catch clause, and the exception is considered handled. The search for handlers stops once the catch clause is finished. Only the matching catch clause executes; it’s not like a switch statement in which you need a break after each case to prevent the remaining ones from executing.

Note that within the try block, a number of different method calls might generate the same exception, but you need only one handler.

3.Termination vs. resumption

There are two basic models in exception handling theory. In termination (which is what Java and C++ support), you assume that the error is so critical that there’s no way to get back to where the exception occurred. Whoever threw the exception decided that there was no way to salvage the situation, and they don’t want to come back.

The alternative is called resumption. It means that the exception handler is expected to do something to rectify the situation, and then the faulting method is retried, presuming success the second time. If you want resumption, it means you still hope to continue execution after the exception is handled. In this case, your exception is more like a method call—which is how you should set up situations in Java in which you want resumption-like behavior. (That is, don’t throw an exception; call a method that fixes the problem.) Alternatively, place your try block inside a while loop that keeps reentering the try block until the result is satisfactory.

Historically, programmers using operating systems that supported resumptive exception handling eventually ended up using termination-like code and skipping resumption. So although resumption sounds attractive at first, it isn’t quite so useful in practice. The dominant reason is probably the coupling that results; your handler must often be aware of where the exception is thrown, and contain nongeneric code specific to the throwing location. This makes the code difficult to write and maintain, especially for large systems where the exception can be generated from many points.

4.The exception specification

In Java, you’re encouraged to inform the client programmer, who calls your method, of the exceptions that might be thrown from your method. This is civilized, because the caller can know exactly what code to write to catch all potential exceptions. Of course, if source code is available, the client programmer could hunt through and look for throw statements, but often a library doesn’t come with sources. To prevent this from being a problem, Java provides syntax (and forces you to use that syntax) to allow you to politely tell the client programmer what exceptions this method throws, so the client programmer can handle them. This is the exception specification and it’s part of the method declaration, appearing after the argument list.

The exception specification uses an additional keyword, throws, followed by a list of all the potential exception types. So your method definition might look like this:

void f() throws TooBig, TooSmall, DivZero { //...

If you say

void f() { // ...

it means that no exceptions are thrown from the method.

5.Performing cleanup with finally

There’s often some piece of code that you want to execute whether or not an exception is thrown within a try block. This usually pertains to some operation other than memory recovery (since that’s taken care of by the garbage collector). To achieve this effect, you use a finally clause at the end of all the exception handlers. The full picture of an exception handling section is thus:

try {

// The guarded region: Dangerous activities

// that might throw A, B, or C

} catch(A a1) {

// Handler for situation A

} catch(B b1) {

// Handler for situation B

} catch(C c1) {

// Handler for situation C

} finally {

// Activities that happen every time

}

From the output, you can see that whether or not an exception is thrown, the finally clause is always executed.

6.Summary

Improved error recovery is one of the most powerful ways that you can increase the robustness of your code. Error recovery is a fundamental concern for every program you write, but it’s especially important in Java, where one of the primary goals is to create program components for others to use. To create a robust system, each component must be robust. By providing a consistent error-reporting model with exceptions, Java allows components to reliably communicate problems to client code.

The goals for exception handling in Java are to simplify the creation of large, reliable programs using less code than currently possible, and to do so with more confidence that your application doesn’t have an unhandled error. Exceptions are one of those features that provide immediate and significant benefits to your project.

this java 错误_java异常错误处理相关推荐

  1. Struts2中我所遇到的内存溢出(java.lang.OutOfMemoryError)异常错误介绍

    1.在我以前写得关于Struts2的文章中,有时候往往会报一些经常出现的错误,今天又出现了,所以特此来介绍一下,并如何解决这种错误. 2.在我们部署项目到Tomcat服务器后,开启Tomcat服务器, ...

  2. oracle返回0001错误,ORACLE 异常错误处理

    本篇主要内容如下: 5.1 异常处理概念 5.1.1 预定义的异常处理 5.1.2 非预定义的异常处理 5.1.3 用户自定义的异常处理 5.1.4  用户定义的异常处理 5.2 异常错误传播 5.2 ...

  3. java出现errors是什么错误_java中错误(error)和异常(exception)有什么主要区别?

    jdk8中文发翻译Throwable类的描述:Throwable类是Java语言中所有错误和异常的Throwable类. 只有作为此类(或其一个子类)的实例的对象由Java虚拟机抛出,或者可以由Jav ...

  4. java 常见错误_Java常见错误的十大列表(前100名!)

    java 常见错误 前10名名单非常受欢迎,有趣且内容丰富. 但是有很多! 如何选择合适的? 这是一个元前10名列表,可帮助您找到前10名的前10名列表. 在更令人讨厌的笔记上: SELECT TOP ...

  5. JAVA安装报1620错误_java安装错误1620

    java安装错误1620 [2021-01-31 02:53:38]  简介: php去除nbsp的方法:首先创建一个PHP代码示例文件:然后通过"preg_replace("/( ...

  6. ORACLE 异常错误处理

    本篇主要内容如下: 5.1 异常处理概念 5.1.1 预定义的异常处理 5.1.2 非预定义的异常处理 5.1.3 用户自定义的异常处理 5.1.4  用户定义的异常处理 5.2 异常错误传播 5.2 ...

  7. [转]ORACLE 异常错误处理

    本文转自:http://www.cnblogs.com/soundcode/archive/2012/01/10/2318385.html 本篇主要内容如下: 5.1 异常处理概念 5.1.1 预定义 ...

  8. python缩进格式错误的是_19个常见的python错误和异常

    19个常见的python错误和异常 错误总是不可避免,尤其是在初学阶段,本文收集整理了1个常见的python错误 1. 忘记添加: 在if, elif, else, for, while, class ...

  9. [推荐]ORACLE PL/SQL编程之五:异常错误处理(知已知彼、百战不殆)

    原文:[推荐]ORACLE PL/SQL编程之五:异常错误处理(知已知彼.百战不殆) [推荐]ORACLE PL/SQL编程之五: 异常错误处理(知已知彼.百战不殆) 继上三篇:ORACLE PL/S ...

最新文章

  1. Appium环境的安装与配置,Python测试脚本测试
  2. 解决jquery的多次绑定事件
  3. c语言中bluetooth函数,C语言中的低功耗蓝牙-使用Bluez创建GATT服务器
  4. 工作186:实际案例解决vue+el-element二级联动,选项选择后不显示的问题
  5. Windows Embedded CE 6.0开发初体验(七)编译和调试平台
  6. 查询 oracle_ORACLE数据库查询语句
  7. SQL*Plus 系统变量之53 - TERM[OUT]
  8. 随想录(vc仿真下的嵌入式开发)
  9. 金山云肖江:5G推动智慧人居产业到达新高度
  10. PwnLnX:针对Linux系统的渗透测试工具
  11. Hacker Rank 上的 Even Tree 小议
  12. 【metasploit】1 渗透测试与metasploit基础介绍 [PTES|msf|armitage安装]
  13. 主板怎么开启csm_B460主板BIOS设置CSM选项无法开启的解决方法
  14. git gui here如何汉化_github的git GUI Here的使用,适合新手!!!
  15. Python生信练习
  16. 在项目中如何做图片优化
  17. XDOJ 317 输出完全二叉树的某一层
  18. java读取otf_在webpack中加载.otf字体文件的正确方法是什么?
  19. springboot入门
  20. PADS VX2.8 敷铜自动倒角的使用方法

热门文章

  1. 程序员,我要为了这个名号而疯狂
  2. 解决微信扫码下载的两个方法
  3. PNP问题学习笔记1
  4. 10个H5页面制作工具,功能全面评测
  5. 基因数据处理54之bwa-mem运行paird-end(1千万条100bp的reads)
  6. 什么是SSD TRIM (by quqi99)
  7. 软考程序员常见问题答疑
  8. Device disconnected
  9. 金山云智能营销平台再升级,AI 投放助力游戏厂商精准到达;微医发布 AI 解决方案,提升县域医疗服务能力...
  10. pytorch导出onnx格式模型时,不固定输入输出维度