创建Java异常来做更多事情而不仅仅是打印消息

时间:2014-12-03 08:43:10

标签: java exception-handling

我正在阅读Effective Java Exception文章

http://www.oracle.com/technetwork/java/effective-exceptions-092345.html

我在文章的第三页

中找到了这一段
  

不要忘记您的异常是完整的Java类型   适应专业领域,方法甚至构造者   可以为您的独特目的塑造。例如,   虚构引发的InsufficientFundsException类型   CheckingAccount processCheck()方法可以包含一个   OverdraftProtection对象,能够转移所需的资金   弥补另一个帐户的不足,其身份取决于如何   支票帐户已设置。

如果我在线检查,我发现自定义异常代码就像这样

public class DivisorCannotbeZeroException extends RuntimeException {


    private static final long serialVersionUID = 1L;

    public DivisorCannotbeZeroException(){
        super();
        System.out.println("I am doing something more");
    }

    public DivisorCannotbeZeroException(String message){
        super(message);
    }

}

即使是print语句也不适用于该代码。能否请您解释一下如何在特定于我们要求的自定义异常类中添加更多功能?

2 个答案:

答案 0 :(得分:3)

你必须构造一个Exception的实例(使用默认构造函数)来调用该构造函数(通常是throw),例如

public static void main(String[] args) {
    throw new DivisorCannotbeZeroException();
}

输出

I am doing something more
Exception in thread "main" com.stackoverflow.Example
    at com.stackoverflow.Example.main(Example.java:18)

答案 1 :(得分:0)

MyException.java(用户定义)

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

CustomException示例

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

    }

可以对任何其他类进行异常,可以继承特定进程的属性