code学习

异常处理机制Try……Catch与Throws

异常处理机制Try……Catch与Throws

try {
    //可能存在异常的代码块
        } catch (UserException e) {
            e.printStackTrace();
        }      

这种处理异常的方式是程序自身捕获异常,自己消化了异常,虚拟机不知道错误的存在,虚拟机不会停止运行,但是该方法停止了

Throws 的处理方式是把错误抛给虚拟机,方法自身没问题,虚拟机会异常停止

打个不太恰当的比方:

boss交给你一个任务,当你遇到问题是,Try……Catch就是自己解决;Throws就是把问题报告给boss,自己一边凉快去;采用前者的结果是升职加薪,后者嘛……卷铺盖走人吧!

举个栗子

定义一个自定义异常(UserException.java)

package com.hk.spring.exception;

public class UserException extends Exception {

    public UserException() {
        super();
    }

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

}      

定义一个上诉异常的子异常(UserNameException.java)

package com.hk.spring.exception;

public class UserNameException extends UserException {

    public UserNameException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public UserNameException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

}      

再定义一个子异常(UserPasswordException.java)

package com.hk.spring.exception;

public class UserPasswordException extends UserException {

    public UserPasswordException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public UserPasswordException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

}      

业务类(SomeService.java)

package com.hk.spring.exception;


public class SomeService {

    public boolean check(String username,String password) throws UserException{
        if("浪丶荡".equals(username.trim())){
            throw new UserNameException("用户名有误");
        }
        if("浪丶荡".equals(password.trim())){
            throw new UserPasswordException("密码有误");
        }
        return true;
    }
}      
package com.hk.spring.exception;


import org.junit.Test;
public class Mytest {

    private SomeService service = new SomeService();

    @Test
    public void testTryCatch(){
        try {
            service.check("浪丶荡", "浪丶荡");
        } catch (UserException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testThrows() throws UserException{
        service.check("浪丶荡", "浪丶荡");
    }
}