异常处理

Creating Custom Exception Classes


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");
			}
		}
	}

}

Exception Handling in Java – Best Practices

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

1.使用特定异常 - Exception层次结构的基类没有提供任何有用的信息,这就是为什么Java有这么多的异常类,比如IOException以及其他子类如FileNotFoundException,EOFException等。我们应该总是抛出并捕获特定的异常类,以便调用者知道 容易发生异常的根本原因并加以处理。 这使调试变得简单并帮助客户端应用程序适当地处理异常。 尽早投掷或失败 - 我们应该尽早抛出异常。

2.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.NullPointerException
	at 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;


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
}

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 null
	at com.journaldev.exceptions.CustomExceptionExample.processFile(CustomExceptionExample.java:37)
	at com.journaldev.exceptions.CustomExceptionExample.main(CustomExceptionExample.java:12)

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

3.晚一点捕获 - 由于java强制要么处理已检查的异常,要么在方法签名中声明它,有时开发人员倾向于捕获异常并记录错误。 但这种做法是有害的,因为调用者程序没有得到任何异常通知。 只有当我们能够妥善处理它时,我们才应该捕获异常。 例如,在上面的方法中,我将异常抛回调用方法来处理它。 其他可能希望以不同方式处理异常的应用程序可以使用相同的方法。 在实现任何功能时,我们应该始终将异常抛回给调用者并让他们决定如何处理它。

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

4.关闭资源 - 由于异常会暂停程序的处理,我们应该关闭finally块中的所有资源,或者使用Java 7 try-with-resources增强功能让java运行时为您关闭它。

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

5.记录异常 - 我们应该始终记录异常消息,同时抛出异常提供明确的消息,以便调用者很容易知道异常发生的原因。 我们应该总是避免使用只占用异常的空catch块,并且不提供任何有意义的调试异常细节。

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

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

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

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

10.Document the Exceptions Thrown – Use javadoc @throws to clearly specify the exceptions thrown by the method, it’s very helpful when you are providing an interface to other applications to use.

转自www.journal.dev

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值