java----异常处理

Throwable是异常的基类

 

 异常处理(try使用):

public class Demo {
    public static void main(String[] args){    	
    	test();
    }
    public static void test(){
    	int[] arr = {1,2,3};
    	try{
    		System.out.print(arr[8]);
    	}catch(ArrayIndexOutOfBoundsException e){
    		System.out.println(e);
    	}
    	catch(Exception e){
    		e.printStackTrace(); //可以打印栈错误信息
    		System.out.println("错误");
    	}finally{
    		System.out.println("无论是否产生异常,都要执行");//即使系统报错,程序会异常退出,也会执行,即使try中有return,finally也会在return之前执行
    	}
    }
}

  

 throws和Throw使用:

public class Demo {
    public static void main(String[] args){    	
    	test();
    }
    public static int test() throws ArrayIndexOutOfBoundsException{
    	Scanner s = new Scanner(System.in);
    	try{
    		int[] arr = {1,2};
    		int x = arr[4];
    		return 1;
    	}catch(ArrayIndexOutOfBoundsException e){
//    		e.printStackTrace();
    		throw new ArrayIndexOutOfBoundsException("出错了");//主动抛出错误
//    		return 1;
    	}
    }
}

  

 自定义错误:

同一个包下创建四个类

Demo.java

public class Demo {
    public static void main(String[] args){    	
    	UserServer userserver = new UserServer();
    	try {//由于MyException继承的是受检异常,调用时就必须捕获。
			User user = userserver.login("admin", "123");
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}

MyException.java

/**
 * @author zhengyan
 *1、自定义异常通常是通过继承一个异常类来实现(Throwable、Exception、RuntimeException)
 *2、通过实现构造方法
 *
 */
public class MyException extends Exception{
	public MyException(){
		super();
	}
	public MyException(String message){
		super(message);
	}
}

User.java

public class User {
	private String name;
	private int age;
	
	public User(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "UserSever [name=" + name + ", age=" + age + "]";
	}
	
}

UserServer.java

public class UserServer {
	public User login(String name,String pwd) throws Exception{
		if(!"admin".equals(name)){
			throw new MyException("用户名错误");
		}
		if(!"123".equals(pwd)){
			throw new MyException("密码错误");
		}
		User user = new User("小明", 18);
		return user;
	}
}

  

 受检异常(Exception)

  调用时必须加上try..catch....

非受检异常(RuntimeException)

  调用时不需要捕获错误,但是最好还try和catch。他属于运行时的错误

在自定义异常的时候,根据需求选择性的使用

 

补充(断言):

assert 1==1:"结果不正确";  如果表达式为true,正常运行,表达式为false,打印结果不正确

使用需要给jvm加上参数。

 

posted @ 2019-04-10 12:03  小名的同学  阅读(146)  评论(0编辑  收藏  举报