smartFramework学习笔记之异常处理解决方案

1、如果抛出了异常,后面的 System.out.println() 语句是绝对不会执行

public class GreetingImpl implements Greeting {

    @Override
    public void sayHello(String name) throws Exception {
        if (name == null) {
            throw new Exception("The name is null.");
        }
        System.out.println("Hello! " + name);   //绝对不会执行
    }
}

2、上文异常是从下往上抛的,在sayHello调用的地方catch

public class Client {

    public static void main(String[] args) {
        Greeting greeting = new GreetingImpl();
        try {
            greeting.sayHello(null);
        } catch (Exception e) {
            System.out.println("Error! Message: " + e.getMessage());
        }
    }
}

3、Checked Exception(受检异常)

  • 必须在try...catch

4、Unchecked Exception(非受检异常)

  • RuntimeException :不用去catch,系统可以自己处理
public class GreetingImpl implements Greeting {

    @Override
    public void sayHello(String name) {
        if (name == null) {
            throw new RuntimeException("The name is null.");//////////非受检异常
        }
        System.out.println("Hello! " + name);
    }
}

5、异常结构

  • 红色的是受检异常,蓝色的是非受检异常

6、自定义异常

7、借鉴 C/C++ 中的“错误代码”编程风格

public class GreetingImpl implements Greeting {

    @Override
    public int sayHello(String name) {
        if (name == null) {
            return 1; // Error: The name is null.
        }
        System.out.println("Hello! " + name);
        return 0; // Success
    }
}

8、对于方法本身就需要返回值的情况:

  • 返回值封装成 JavaBean 
public class Result extends BaseBean {

    private boolean success = true;
    private int error = 0;
    private Object data = null;

    public Result(boolean success) {
        this.success = success;
    }

    public Result data(Object data) {
        this.data = data;
        return this;
    }

    public Result error(int error) {
        this.error = error;
        return this;
    }
...
}

《《《《《《《《《《try...catch挺好的》》》》》》》》》》》》》》》》》》》》》

猜你喜欢

转载自my.oschina.net/u/3847203/blog/1814580