JAVA基础学习笔记_异常

异常

应该知道出了异常怎么处理

  • java.lang.Throwable
    • Error(错误,硬件出错或内存不足,不是程序员能解决的)
    • Exception(异常)
      • RuntimeException(运行时异常),代码出错导致程序出现的问题
      • 其他异常(编译时异常),提醒程序员检查本地信息
        java–(编译)–>字节码文件(class)—(运行)–>运行结果

异常的作用

  • 异常是查询bug的关键信息
  • 异常可以作为方法内部的一种特殊返回值,以便通知调用着底层的执行情况

处理异常的方式

  • 默认处理,将异常异常信息打印在控制台
  • 捕获异常(自己处理),好处就是可以让程序继续执行不停止为了不让程序停止
  • 抛出异常,在方法中出现异常,就没有继续运行的意义了,抛出处理告诉调用者出错了
public static void main(String[] args) {
   int[] arr = {1,2,3,4,5};
   try {
   	System.out.println(arr[10]);
   }
   catch (ArrayIndexOutOfBoundsException e) {
   	System.out.println(e);
   }
}

异常中的常见方法

  • e.getMessage()
  • e.toString()
  • e.printStackTrace()
public static void main(String[] args) {
   int[] arr = {1,2,3,4,5};
   try {
   	System.out.println(arr[10]);
   }
   catch (ArrayIndexOutOfBoundsException e) {
   	String message = e.getMessage();//Index 10 out of bounds for length 5
   	System.out.println(message);
   	String string = e.toString();//java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5
   	System.out.println(string);
   	e.printStackTrace();
   	//输出信息最为详尽
   	//java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5at com.itheima.exception.exception.main(exception.java:7)
   }
}

捕获异常

你比如说,这个信息是用户来输入的,如果不抛出异常捕获异常,不能用户输入错一次,我们整个java程序就停了吧,那还搞什么网页

public static void main(String[] args) {
	//创建键盘录入对象
	Scanner sc = new Scanner(System.in);
	//创建女朋友对象
	GirlFriend girlFriend = new GirlFriend();
	while (true) {
		try {
			//接受女友姓名
			String name = sc.nextLine();
			//设置女友姓名
			girlFriend.setName(name);
			//接受女友年龄
			int age = sc.nextInt();
			//设置女友年龄
			girlFriend.setAge(age);
			break;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	System.out.println(girlFriend);
}
public class GirlFriend {
    String name;
    int age;

    public GirlFriend() {
    }

    public GirlFriend(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        if(name.length()>10||name.length()<3){
            throw new RuntimeException();
        }
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        if(age<18){
            throw new RuntimeException();
        }
        this.age = age;
    }

    public String toString() {
        return "GirlFriend{name = " + name + ", age = " + age + "}";
    }
}

自定义异常

自定义的异常类继承RuntimeException就可以了
注意要重写空参构造和带参构造,不仅是这里注意,所有的类继承父类都不能忘写构造方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值