什么是异常?
程序在其生命周期中并不总是能够平稳运行。 有时,它会遇到意外情况,例如用户输入错误的输入,网络连接断开,数据库崩溃或磁盘已满等。这种情况称为异常情况,通常会导致程序异常从而停止执行。
作为程序员,我们应该处理这些特殊情况,以便与用户进行友好的交互,并让程序继续正常执行,而不是使程序崩溃或死亡。 因此,术语“异常处理”。
假如程序需要接收数字值,而你提供的是字符,那么程序就会报异常
该程序立即停止。 我们期望该程序能够处理此错误输入,并继续要求用户重新输入。 我将在下面向您展示如何处理此异常。
为什么使用异常处理?
通过使用JDK提供的强大的异常处理机制,您将能够编写可靠而安全的程序,这些程序旨在正确地处理错误和异常。
假设您正在开发一个从Internet下载信息的程序。如果在下载过程中网络连接断开,该怎么办?
如果您处理这种特殊情况(可能随时发生),程序将提示用户等待直到连接恢复并继续下载。用户会很高兴,因为他或她了解了有关情况,并且程序能够无缝运行。
但是,如果您不介意处理该怎么办?当然,该程序可能会直接停止造成不好的体验
通过应用异常处理,可以使程序更可靠,更稳定,最重要的是,可以生成高质量的软件应用程序。
处理异常应该是您日常编码中的习惯。现在,我们将了解如何以Java编程语言实现它。
java如何实现异常处理
Java is an object-oriented programming language so it provides object-oriented ways for handling errors and exceptions. Unlike procedural programming languages like C/C++, which allow us to handle errors by checking return codes of a method, Java uses a different approach(途径): the throw and try-catch mechanism.
异常处理的机制: Code that may generate error at runtime will throw an exception if the error occurs. An exception here is an object of a special class that implements the java.lang.Throwable interface. The exception class name represents the error and the exception object conveys the detailed information such as line number, method name and class name where the exception origins. This information is very helpful for debugging and solving the errors. For example, the Divider program above may throw NumberFormatException
if the input is not number, or ArrayIndexOutOfBoundsException
if we don’t provide numbers in the command line’s arguments. These are just two of various exceptions defined by JDK. You may also hear about NullPointerException
and IllegalArgumentException
。
We try to execute the code that may throw exceptions in the tryblock, and if it does, code in the catch block gets executed to handle the exceptions.