尝试抓块创建干净代码的最佳做法是什么? [英] What is the Best practice for try catch blocks to create clean code?

查看:117
本文介绍了尝试抓块创建干净代码的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JAVA或C#中的异常管理的最佳做法


我今天早些时候阅读了关于stackoverflow的一个问题这让我想起了处理异常的最佳做法。



所以,我的问题是处理例外的最佳做法 产生干净,高品质的代码



这是我的代码,我觉得这很安静,但如果我错了,请让我知道还是不清楚!
我试图记住方法中的可测试性和相同的抽象级别。



欢迎每一个建设性的评论。 :)

  import java.awt.Point; 
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/ **
*< p>这是一个虚拟代码< / p>
*目标是提供例外分离和处理的最佳做法。
* /
public class ExceptionHandlingDemo {
// System.out不是一个好习惯。使用记录器也是很好的测试(可以检查是否产生预期的错误消息)。
private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

//无法使用的列表< Point>
私有接口PointList extends List< Point> {}

/ **
*从文件加载点列表的方法。
* @param path - 要加载的文件的路径和名称。
*前提条件:路径不能{@code null}。在这种情况下,将抛出{@link NullPointerException}。
*后置条件:如果文件不存在,则会发生一些IOException异常,或者该文件不包含列表,返回的对象为{@code null}。
* * /
/ *(Google抛出NullpointerExceptio),因为开发人员不禁止它。我知道这是有争议的,但是现在已经不在话题了。 * /
public List< Point> loadPointList(final String path){
Preconditions.checkNotNull(path,文件的路径不能为空);

列表<点> pointListToReturn = null;
ObjectInputStream in = null;

try {
in = openObjectInputStream(path);
pointListToReturn = readPointList(in);
} catch(final Throwable throwable){
handleException(throwable);
} finally {
close(in);
}

return pointListToReturn;
}

/ * ========现在私人助手方法======== * /

private ObjectInputStream openObjectInputStream( final String filename)throws FileNotFoundException,IOException {
return new ObjectInputStream(new FileInputStream(filename));
}

私人列表<点> readPointList(final ObjectInputStream objectInputStream)throws IOException,ClassNotFoundException {
final Object object = objectInputStream.readObject();

列表<点> ret = null;

if(Object instanceof PointList){
ret =(PointList)object;
}
return ret;
}

private void handleException(final Throwable throwable){
//我不知道这里的最佳做法...
logger.error(throwable)的toString());
}

private void close(final Closeable closeable){
if(可关闭!= null){
try {
closeable.close();
} catch(IOException e){
logger.error(Failed closing:%s,可关闭);
}
}
}

/ * ======== Getter和setter现在。 ======== * /

// ...

/ **
* @param args
* /
public static void main(String [] args){
ExceptionHandlingDemo test = new ExceptionHandlingDemo();
test.loadPointList(test-filename.ext);
}
}

EDITED: p>

我想避免的是在彼此之间编写大量的catch事件...

解决方案

乍一看几个建议:


  1. 你不应该抓住 Throwable 而是尽可能地捕获异常的特定。捕获 Throwable 的麻烦是包含错误类,如 OutOfMemoryError 等。你想让他们通过(因为某些原因而被取消选择)。

  2. 当你记录异常时,总是传递异常,而不仅仅是它的的toString()

  3. 您可能不希望使用一般的异常处理方法。

所以在你遇到异常的地方你想要这样的东西:

 } catch(IOException e){ 
logger.error(一些相关消息,e);
//现在处理例外情况
}

消息应包括一些上下文信息如果可能的话。任何可能有助于通过日志狩猎来追踪问题的消息。


Possible Duplicate:
Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear! I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 * <p>This is a dummy code.</p>
 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown. 
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) { 
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}

EDITED:

What I want to avoid is writing lot of catch cases after each other...

解决方案

A few suggestions at first glance:

  1. You shouldn't catch Throwable and instead catch as specific of an exception as possible. The trouble with catching Throwable is that will include Error classes like OutOfMemoryError and the like. You want to let those pass through (they're unchecked for a reason).
  2. When you log exceptions always pass the exception and not just its toString(). It's very hard to diagnose problems without the stack trace.
  3. You probably don't want a general exception handling method.

So at places you catch exceptions you want something like this:

} catch (IOException e) {
    logger.error("some relevant message", e);
    // now handle the exception case
}

The message should include some contextual information if possible. Anything that might help tracking down the problem when someone is hunting through logs.

这篇关于尝试抓块创建干净代码的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆