肿瘤康复网,内容丰富有趣,生活中的好帮手!
肿瘤康复网 > java 异常处理发生异常_Java中的异常处理

java 异常处理发生异常_Java中的异常处理

时间:2023-09-28 04:22:42

相关推荐

java 异常处理发生异常

Exception Handling in Java is a very interesting topic. Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known asJava Exception Handling. We will look into following topics in this tutorial.

Java中的异常处理是一个非常有趣的主题。 异常是可能在程序执行期间发生的错误事件,它会破坏其正常流程。 Java提供了一种健壮且面向对象的方式来处理异常情况,称为Java异常处理。 我们将在本教程中研究以下主题。

Java中的异常处理 (Exception Handling in Java)

Exception Handling in Java – OverviewJava中的异常处理–概述 Java Exception Handling KeywordsJava异常处理关键字 Java Exception HierarchyJava异常层次结构 Exception Handling in Java – Useful MethodsJava中的异常处理–有用的方法 Java 7 Automatic Resource Management and Catch block improvementsJava 7自动资源管理和捕获块改进 Exception Handling in Java – Creating Custom Exception ClassesJava中的异常处理–创建自定义异常类 Exception Handling in Java – Best PracticesJava中的异常处理–最佳实践

Java中的异常处理–概述 (Exception Handling in Java – Overview)

We don’t like exceptions but we always have to deal with them, great news is that Exception handling in Java is very robust and easy to understand and use. Exceptions in java can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure, Database server down etc. In this section, we will learn how exceptions are handled in java.

我们不喜欢异常,但是我们总是要处理它们,一个好消息是Java中的异常处理非常健壮并且易于理解和使用。 Java中的异常可能源于各种情况,例如用户输入的错误数据,硬件故障,网络连接故障,数据库服务器关闭等。在本节中,我们将学习如何在Java中处理异常。

Java being an object oriented programming language, whenever an error occurs while executing a statement, creates anexception objectand then the normal flow of the program halts and JRE tries to find someone that can handle the raised exception. The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. When the exception occurs in a method, the process of creating the exception object and handing it over to runtime environment is called“throwing the exception”.

Java是一种面向对象的编程语言,只要在执行语句时发生错误,就会创建一个异常对象,然后程序的正常流程将停止, JRE会尝试寻找可以处理引发异常的人。 异常对象包含许多调试信息,例如方法层次结构,发生异常的行号,异常类型等。当方法中发生异常时,将调用创建异常对象并将其移交给运行时环境的过程。“抛出异常”

Once runtime receives the exception object, it tries to find the handler for the exception. Exception Handler is the block of code that can process the exception object. The logic to find the exception handler is simple – starting the search in the method where error occurred, if no appropriate handler found, then move to the caller method and so on. So if methods call stack is A->B->C and exception is raised in method C, then the search for appropriate handler will move from C->B->A. If appropriate exception handler is found, exception object is passed to the handler to process it. The handler is said to be“catching the exception”. If there are no appropriate exception handler found then program terminates printing information about the exception.

运行时一旦接收到异常对象,它将尝试查找该异常的处理程序。 异常处理程序是可以处理异常对象的代码块。 查找异常处理程序的逻辑很简单–在发生错误的方法中开始搜索,如果找不到合适的处理程序,则转到调用者方法,依此类推。 因此,如果方法调用堆栈为A-> B-> C且方法C中引发了异常,则对适当处理程序的搜索将从C-> B-> A转移。 如果找到合适的异常处理程序,则将异常对象传递给该处理程序以对其进行处理。 据说处理程序正在“捕获异常”。 如果找不到合适的异常处理程序,则程序将终止有关异常的打印信息。

Note that Java Exception handling is a framework that is used to handle runtime errors only, compile time errors are not handled by exception handling in java.

请注意,Java异常处理是仅用于处理运行时错误的框架,Java中的异常处理不处理编译时错误。

We use specific keywords in java program to create an exception handler block, we will look into these keywords next.

我们在Java程序中使用特定的关键字来创建异常处理程序块,接下来我们将研究这些关键字。

Java异常处理关键字 (Java Exception Handling Keywords)

Java provides specific keywords for exception handling purposes, we will look after them first and then we will write a simple program showing how to use them for exception handling.

Java提供了用于异常处理目的的特定关键字,我们将首先照顾它们,然后编写一个简单的程序,展示如何使用它们进行异常处理。

throw– We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null.throwkeyword is used to throw exception to the runtime to handle it.throw–我们知道,如果发生任何异常,将创建一个异常对象,然后Java运行时开始处理以处理它们。 有时我们可能想在代码中显式生成异常,例如,在用户身份验证程序中,如果密码为null,则应向客户端抛出异常。throw关键字用于向运行时抛出异常以对其进行处理。throws– When we are throwing any exception in a method and not handling it, then we need to usethrowskeyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.throws–当我们在方法中抛出任何异常而不对其进行处理时,我们需要在方法签名中使用throws关键字,以使调用程序知道该方法可能抛出的异常。 调用方方法可以处理这些异常,也可以使用throws关键字将其传播到其调用方方法。 我们可以在throws子句中提供多个异常,它也可以与main()方法一起使用。try-catch– We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.try-catch–我们在代码中使用try-catch块进行异常处理。 try是块的开始,catch是try块的末尾,用于处理异常。 我们可以使用try捕获多个catch块,并且try-catch块也可以嵌套。 catch块需要一个应为Exception类型的参数。finally– finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.最终–最终块是可选的,只能与try-catch块一起使用。 由于异常会暂停执行过程,因此我们可能会打开一些不会关闭的资源,因此我们可以使用finally块。 无论是否发生异常,finally块都会始终执行。

Let’s see a simple programing showing exception handling in java.

让我们看一个简单的程序,显示Java中的异常处理。

package com.journaldev.exceptions;import java.io.FileNotFoundException;import java.io.IOException;public class ExceptionHandling {public static void main(String[] args) throws FileNotFoundException, IOException {try{testException(-5);testException(-10);}catch(FileNotFoundException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}finally{System.out.println("Releasing resources");}testException(15);}public static void testException(int i) throws FileNotFoundException, IOException{if(i < 0){FileNotFoundException myException = new FileNotFoundException("Negative Integer "+i);throw myException;}else if(i > 10){throw new IOException("Only supported for index 0 to 10");}}}

Output of above program is:

上面程序的输出是:

java.io.FileNotFoundException: Negative Integer -5at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:24)at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:10)Releasing resourcesException in thread "main" java.io.IOException: Only supported for index 0 to 10at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:27)at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:19)

Notice that testException() method is throwing exception using throw keyword and method signature uses throws keyword to let caller know the type of exceptions it might throw. In main() method, I am handling exception using try-catch block in main() method and when I am not handling it, I am propagating it to runtime with throws clause in main method. Notice thattestException(-10)never gets executed because of exception and then execution of finally block after try-catch block is executed. The printStackTrace() is one of the useful method in Exception class and used for debugging purpose.

请注意,testException()方法使用throw关键字引发异常,方法签名使用throws关键字告知调用方它可能引发的异常类型。 在main()方法中,我正在使用main()方法中的try-catch块来处理异常,当我不处理它时,我将通过main方法中的throws子句将其传播到运行时。 请注意,testException(-10)永远不会因为异常而执行,然后在try-catch块执行后再执行finally块。 printStackTrace()是Exception类中的一种有用方法,用于调试目的。

We can’t have catch or finally clause without a try statement.没有try语句,我们不能有catch或finally子句。 A try statement should have either catch block or finally block, it can have both blocks.一个try语句应该具有catch块或finally块,它可以同时具有两个块。 We can’t write any code between try-catch-finally block.我们不能在try-catch-finally块之间编写任何代码。 We can have multiple catch blocks with a single try statement.一个try语句可以包含多个catch块。 try-catch blocks can be nested similar to if-else statements.try-catch块可以类似于if-else语句进行嵌套。 We can have only one finally block with a try-catch statement.我们只有一个带有try-catch语句的finally块。

Java异常层次结构 (Java Exception Hierarchy)

As stated earlier, when any exception is raised anexception objectis getting created. Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.

如前所述,当引发任何异常时,将创建一个异常对象。 Java异常是分层的, 继承用于对不同类型的异常进行分类。 Throwable是Java异常层次结构的父类,它具有两个子对象–错误和异常。 异常进一步分为检查异常和运行时异常。

Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That’s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError.错误:错误是超出应用程序范围的特殊情况,无法预见并从中恢复,例如硬件故障,JVM崩溃或内存不足错误。 这就是为什么我们有一个单独的错误层次结构,并且我们不应该尝试处理这些情况。 一些常见的错误是OutOfMemoryError和StackOverflowError。Checked Exceptions: Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exception is the parent class of all Checked Exceptions and if we are throwing a checked exception, we must catch it in the same method or we have to propagate it to the caller using throws keyword.检查异常:检查异常是我们可以在程序中预期并尝试从程序中恢复的异常情况,例如FileNotFoundException。 我们应该捕获此异常,并向用户提供有用的消息,并正确记录它以进行调试。 Exception是所有Checked Exceptions的父类,如果要抛出一个Checked异常,则必须在同一方法中捕获它,否则必须使用throws关键字将其传播给调用方。Runtime Exception: Runtime Exceptions are cause by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throwArrayIndexOutOfBoundExceptionat runtime. RuntimeException is the parent class of all runtime exceptions. If we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming.运行时异常:运行时异常是由不良编程引起的,例如,尝试从数组中检索元素。 在尝试检索元素之前,我们应该首先检查数组的长度,否则它可能会在运行时引发ArrayIndexOutOfBoundException。 RuntimeException是所有运行时异常的父类。 如果我们在方法中引发任何运行时异常,则无需在方法签名throws子句中指定它们。 更好的编程可以避免运行时异常。

Java中的异常处理–有用的方法 (Exception Handling in Java – Useful Methods)

Java Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable. The exception classes are created to specify different kind of exception scenarios so that we can easily identify the root cause and handle the exception according to it’s type. Throwable class implements Serializable interface for interoperability.

Java Exception及其所有子类均未提供任何特定方法,并且所有方法均在Throwable基类中定义。 创建异常类是为了指定不同类型的异常情况,以便我们可以轻松识别根本原因并根据异常类型进行处理。 Throwable类实现Serializable接口以实现互操作性。

Some of the useful methods of Throwable class are;

Throwable类的一些有用方法是;

public String getMessage()– This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.public String getMessage()–此方法返回Throwable消息字符串,并且可以在通过其构造函数创建异常时提供该消息。public String getLocalizedMessage()– This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply usegetMessage()method to return the exception message.public String getLocalizedMessage()–提供此方法,以便子类可以重写它以向调用程序提供特定于语言环境的消息。 此方法的可抛出类实现仅使用getMessage()方法即可返回异常消息。public synchronized Throwable getCause()– This method returns the cause of the exception or null id the cause is unknown.公共同步Throwable getCause()–此方法返回异常的原因,或者返回null id,原因未知。public String toString()– This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.public String toString()–此方法以String格式返回有关Throwable的信息,返回的String包含Throwable类的名称和本地化消息。public void printStackTrace()– This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.public void printStackTrace()–此方法将堆栈跟踪信息打印到标准错误流,此方法已重载,我们可以传递PrintStream或PrintWriter作为参数,以将堆栈跟踪信息写入文件或流。

Java 7自动资源管理和捕获块改进 (Java 7 Automatic Resource Management and Catch block improvements)

If you are catching a lot of exceptions in a single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the feature was improved catch block where we can catch multiple exceptions in a single catch block. The catch block with this feature looks like below:

如果您在单个try块中捕获了很多异常,则您会注意到catch块代码看起来非常丑陋,并且主要由用于记录错误的冗余代码组成,请记住,Java 7的功能之一是改进了catch块,我们可以在单个catch块中捕获多个异常。 具有此功能的catch块如下所示:

catch(IOException | SQLException ex){logger.error(ex);throw new MyException(ex.getMessage());}

There are some constraints such as the exception object is final and we can’t modify it inside the catch block, read full analysis at Java 7 Catch Block Improvements.

存在一些约束,例如异常对象是最终对象,我们无法在catch块内对其进行修改,请在Java 7 Catch Block Improvements上阅读完整的分析。

Most of the time, we use finally block just to close the resources and sometimes we forget to close them and get runtime exceptions when the resources are exhausted. These exceptions are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So java 7 one of the improvement was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of try-catch block, runtime environment automatically close these resources. Sample of try-catch block with this improvement is:

在大多数情况下,我们使用finally块只是为了关闭资源,有时我们忘记关闭它们并在资源耗尽时获取运行时异常。 这些异常很难调试,我们可能需要调查使用该类型资源的每个位置,以确保将其关闭。 因此,java 7的改进之一是try-with-resources,我们可以在try语句本身中创建资源,并在try-catch块内使用它。 当执行从try-catch块执行时,运行时环境会自动关闭这些资源。 具有这种改进的try-catch块示例为:

try (MyResource mr = new MyResource()) {System.out.println("MyResource created in try-with-resources");} catch (Exception e) {e.printStackTrace();}

Read a detailed explanation of this feature at Java 7 Automatic Resource Management.

在Java 7自动资源管理中阅读有关此功能的详细说明。

Java中的异常处理–创建自定义异常类 (Exception Handling in Java – Creating Custom Exception Classes)

Java provides a lot of exception classes for us to use but sometimes we may need to create our own custom exception classes to notify the caller about specific type of exception with appropriate message and any custom fields we want to introduce for tracking, such as error codes. For example, let’s say we write a method to process only text files, so we can provide caller with appropriate error code when some other type of file is sent as input.

Java提供了许多异常类供我们使用,但有时我们可能需要创建自己的自定义异常类,以通过适当的消息以及我们要引入以进行跟踪的任何自定义字段(例如错误代码)来通知调用方有关特定类型的异常的信息。 。 例如,假设我们编写了一种仅处理文本文件的方法,因此当某些其他类型的文件作为输入发送时,我们可以为调用者提供适当的错误代码。

Here is an example of custom exception class and showing it’s usage.

这是自定义异常类的示例,并显示了其用法。

package com.journaldev.exceptions;public class MyException extends Exception {private static final long serialVersionUID = 4664456874499611218L;private String errorCode="Unknown_Exception";public MyException(String message, String errorCode){super(message);this.errorCode=errorCode;}public String getErrorCode(){return this.errorCode;}}

package com.journaldev.exceptions;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;public class CustomExceptionExample {public static void main(String[] args) throws MyException {try {processFile("file.txt");} catch (MyException e) {processErrorCodes(e);}}private static void processErrorCodes(MyException e) throws MyException {switch(e.getErrorCode()){case "BAD_FILE_TYPE":System.out.println("Bad File Type, notify user");throw e;case "FILE_NOT_FOUND_EXCEPTION":System.out.println("File Not Found, notify user");throw e;case "FILE_CLOSE_EXCEPTION":System.out.println("File Close failed, just log it.");break;default:System.out.println("Unknown exception occured, lets log it for further debugging."+e.getMessage());e.printStackTrace();}}private static void processFile(String file) throws MyException {InputStream fis = null;try {fis = new FileInputStream(file);} catch (FileNotFoundException e) {throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION");}finally{try {if(fis !=null)fis.close();} catch (IOException e) {throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION");}}}}

Notice that we can have a separate method to process different types of error codes that we get from different methods, some of them gets consumed because we might not want to notify user for that or some of them we will throw back to notify user for the problem.

请注意,我们可以有一个单独的方法来处理从不同方法中获取的不同类型的错误代码,其中一些被消耗掉是因为我们可能不想为此通知用户,或者其中一些我们将返回以通知用户问题。

Here I am extending Exception so that whenever this exception is being produced, it has to be handled in the method or returned to the caller program, if we extends RuntimeException, there is no need to specify it in the throws clause. This is a design decision but I always like checked exceptions because I know what exceptions I can get when calling any method and take appropriate action to handle them.

在这里,我扩展了Exception,以便每当产生此异常时,都必须在方法中对其进行处理或将其返回给调用程序,如果我们扩展RuntimeException,则无需在throws子句中指定它。 这是一个设计决策,但是我始终喜欢检查异常,因为我知道调用任何方法并采取适当的措施来处理它们时可以得到哪些异常。

Java中的异常处理–最佳实践 (Exception Handling in Java – Best Practices)

Use Specific Exceptions– Base classes of Exception hierarchy doesn’t provide any useful information, thats why Java has so many exception classes, such as IOException with further sub-classes as FileNotFoundException, EOFException etc. We should always throw and catch specific exception classes so that caller will know the root cause of exception easily and process them. This makes debugging easy and helps client application to handle exceptions appropriately.使用特定的异常-异常层次结构的基类没有提供任何有用的信息,这就是Java具有这么多异常类的原因,例如IOException以及其他子类,如FileNotFoundException,EOFException等。我们应该始终抛出并捕获特定的异常类,因此该调用者将很容易知道异常的根本原因并进行处理。 这使调试变得容易,并帮助客户端应用程序适当地处理异常。Throw Early or Fail-Fast– We should try to throw exceptions as early as possible. Consider above processFile() method, if we pass null argument to this method we will get following exception.

Exception in thread "main" java.lang.NullPointerExceptionat java.io.FileInputStream.<init>(FileInputStream.java:134)at java.io.FileInputStream.<init>(FileInputStream.java:97)at com.journaldev.exceptions.CustomExceptionExample.processFile(CustomExceptionExample.java:42)at com.journaldev.exceptions.CustomExceptionExample.main(CustomExceptionExample.java:12)

While debugging we will have to look out at the stack trace carefully to identify the actual location of exception. If we change our implementation logic to check for these exceptions early as below;

Then the exception stack trace will be like below that clearly shows where the exception has occurred with clear message.

com.journaldev.exceptions.MyException: File name can't be nullat com.journaldev.exceptions.CustomExceptionExample.processFile(CustomExceptionExample.java:37)at com.journaldev.exceptions.CustomExceptionExample.main(CustomExceptionExample.java:12)

尽早抛出或失败-我们应该尽早抛出异常。 考虑上面的processFile()方法,如果将null参数传递给此方法,则会得到以下异常。

在调试时,我们将必须仔细查看堆栈跟踪,以识别异常的实际位置。 如果我们更改实现逻辑以如下所述检查这些异常;

private static void processFile(String file) throws MyException {if(file == null) throw new MyException("File name can't be null", "NULL_FILE_NAME");//further processing}

然后,异常堆栈跟踪将如下所示,以清晰的消息清楚地显示异常发生的位置。

Catch Late– Since java enforces to either handle the checked exception or to declare it in method signature, sometimes developers tend to catch the exception and log the error. But this practice is harmful because the caller program doesn’t get any notification for the exception. We should catch exception only when we can handle it appropriately. For example, in above method I am throwing exception back to the caller method to handle it. The same method could be used by other applications that might want to process exception in a different manner. While implementing any feature, we should always throw exceptions back to the caller and let them decide how to handle it.延迟捕获-由于Java强制处理已检查的异常或在方法签名中声明它,因此有时开发人员倾向于捕获异常并记录错误。 但是这种做法是有害的,因为调用程序不会收到有关该异常的任何通知。 仅当我们可以适当地处理异常时,才应捕获异常。 例如,在上述方法中,我将异常抛出给调用方方法以进行处理。 可能希望以不同方式处理异常的其他应用程序可以使用相同的方法。 在实现任何功能时,我们应始终将异常抛出给调用者,并让他们决定如何处理它。Closing Resources– Since exceptions halt the processing of program, we should close all the resources in finally block or use Java 7 try-with-resources enhancement to let java runtime close it for you.关闭资源–由于异常会中断程序的处理,因此我们应在finally块中关闭所有资源,或使用Java 7 try-with-resources增强功能让Java运行时为您关闭它。Logging Exceptions– We should always log exception messages and while throwing exception provide clear message so that caller will know easily why the exception occurred. We should always avoid empty catch block that just consumes the exception and doesn’t provide any meaningful details of exception for debugging.记录异常–我们应始终记录异常消息,并在抛出异常时提供清晰的消息,以便调用者可以轻松知道发生异常的原因。 我们应该始终避免空的catch块,它只​​会消耗异常,并且不会为调试提供任何有意义的异常细节。Single catch block for multiple exceptions– Most of the times we log exception details and provide message to the user, in this case we should use java 7 feature for handling multiple exceptions in a single catch block. This approach will reduce our code size and it will look cleaner too.用于多个异常的单个catch块–大多数时候,我们记录异常详细信息并向用户提供消息,在这种情况下,我们应该使用Java 7功能在单个catch块中处理多个异常。 这种方法将减少我们的代码大小,并且看起来也会更干净。Using Custom Exceptions– It’s always better to define exception handling strategy at the design time and rather than throwing and catching multiple exceptions, we can create a custom exception with error code and caller program can handle these error codes. Its also a good idea to create a utility method to process different error codes and use it.使用自定义异常–最好在设计时定义异常处理策略,而不是抛出并捕获多个异常,我们可以使用错误代码创建自定义异常,并且调用程序可以处理这些错误代码。 创建实用程序方法来处理不同的错误代码并使用它也是一个好主意。Naming Conventions and Packaging– When you create your custom exception, make sure it ends with Exception so that it will be clear from name itself that it’s an exception. Also make sure to package them like it’s done in JDK, for example IOException is the base exception for all IO operations.命名约定和打包–创建自定义异常时,请确保它以Exception结尾,以便从名称本身就可以清楚看出它是一个异常。 还要确保像在JDK中一样包装它们,例如IOException是所有IO操作的基本异常。Use Exceptions Judiciously– Exceptions are costly and sometimes it’s not required to throw exception at all and we can return a boolean variable to the caller program to indicate whether an operation was successful or not. This is helpful where the operation is optional and you don’t want your program to get stuck because it fails. For example, while updating the stock quotes in database from a third party webservice, we may want to avoid throwing exception if the connection fails.明智地使用异常–异常代价高昂,有时甚至根本不需要引发异常,我们可以向调用者程序返回一个布尔变量,以指示操作是否成功。 如果操作是可选的,并且您不希望程序由于失败而卡住,则这很有用。 例如,在从第三方Web服务更新数据库中的股票报价时,如果连接失败,我们可能希望避免引发异常。Document the Exceptions Thrown– Use javadoc@throwsto clearly specify the exceptions thrown by the method, it’s very helpful when you are providing an interface to other applications to use.记录抛出的异常–使用javadoc@throws明确指定方法抛出的异常,当您提供要使用的其他应用程序的接口时,这将非常有用。

That’s all for exception handling in java, I hope you liked it and learned something from it.

这就是Java中异常处理的全部,希望您喜欢它并从中学到一些东西。

翻译自: /1696/exception-handling-in-java

java 异常处理发生异常

如果觉得《java 异常处理发生异常_Java中的异常处理》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。