JAVA自定义异常

一、关键字解释:

1.try catch:这之间包含的代码如果出现异常时捕获并处理,如果代码之间有错误 ,不影响程序继续执行下去;

2.throw:是在程序中明确引发的异常,比如 throw new Exception();

3.throws:表明方法可能会引发异常,通过throw new Exception()引入异常类,在方法内部并不处理这个异常;通过使用tyr catch语句处理异常;

4.finally:不管有无异常程序段都会执行这段代码

二、Exception类常用方法:

构造方法: public Exception();

 public Exception(String s): // 字符串s是对该异常的描述;

异常处理方法:

public String toString():返回当前异常对象信息的描述;

public String getMessage();返回当前异常对象信息的详细描述;

public void printStackTrace():用来跟踪异常事件发生时执行堆栈内容;

三、自定义异常的实例 :

//登录信息的校验

import java.util.*;
class ExceptLgn extends RuntimeException{ // 自定义异常
    ExceptLgn(){
        super(" 输入的用户名或者密码错误,请重新输入");
    }
}

class ConnectServer{
    private final String id="test";
    private final String pwd="123456";
    void connect(String id,String pwd) throws ExceptLgn{  //方法声明调用自定义异常
        if(this.id.equals(id)&&this.pwd.equals(pwd)){
            System.out.println("模拟登录服务器成功");
        }else{
            throw new ExceptLgn(); // 抛出一个对象
        }
    }
}

public class ExceptionLogin {
    public void login (String id,String pwd){
        ConnectServer cs=new ConnectServer();
        try{
        cs.connect(id,pwd);
        }catch(RuntimeException e){
            //System.out.println(e.getMessage()); //执行此方法时抛出异常
            System.out.println(e.toString());
        }
    }
  public static void main(String[] args){
      ExceptionLogin ext=new ExceptionLogin();
      Scanner sc=new Scanner(System.in);
      System.out.println("请输入用户名和密码:");
       String id=sc.nextLine();
       String pwd=sc.nextLine();
      ext.login(id, pwd);
      
  }
   

 

posted @ 2018-05-16 15:47  zeyuxi  阅读(161)  评论(0编辑  收藏  举报