Java的第五次学习笔记

Java自学笔记5


前言

第五次学习笔记,加油加油,坚持就是胜利!

第十章 异常

一、什么是异常

在这里插入图片描述

二、异常处理

1、代码实现

public class ExceptionDemo {
    public static int division(int num1,int num2) {
    	System.out.println("计算除法前");
    	int result = Integer.MAX_VALUE;
    	try {
    		result = num1/num2;
    	}catch(Exception e) {
    		System.out.println("异常信息:"+e.getMessage());
    	}
    	System.out.println("计算除法后");
    	return result;
    }
    public static void main(String[] args) {
    	int result = division(3,0);
    	System.out.println("result="+result);
    }
}

2、处理机制

在这里插入图片描述

3、层次结构

在这里插入图片描述

三、异常分类

1、常见的异常类型

在这里插入图片描述

2、代码实现


public class UnCheckedException {

	public static void main(String[] args) {
		String value = null;
		System.out.println(value.toString());
		
		String strValue = "123a";
		int value1 = Integer.parseInt(strValue);
		System.out.println(value1);
        
		Person p = new Person();
		
		Student stu =(Student)p;
	}

}
class Person{
	
}
class Student extends Person{
	
}

四、try-catch-finaly

1、说明

在这里插入图片描述
在这里插入图片描述

2、代码实现

import java.util.Scanner;

public class InputMismatchExceptionDemo {

	public static void main(String[] args) {
	    Scanner input = new Scanner(System.in);
	    System.out.println("请输入年龄(必须是整型数字):");
	    int age = -1;
	    try {
	    	age = input.nextInt();
	    }catch(Exception e) {
	    	e.printStackTrance(System.err);
	    }
        System.out.println("输入的年龄是:"+age);
	}

}

五、总结

在这里插入图片描述

代码实现:


public class DivisionDemo {
    public static void division(String strNum1,String strNum2)throws ArithmeticException,NumberFormatException{
	int num1 = Integer.parseInt(strNum1);
    int num2 = Integer.parseInt(strNum2);
    int result = num1/num2;
    System.out.println("result = "+result);
}
	public static void main(String[] args) {
		try {
			division("135","abc");
	}catch (Exception e) {
		e.printStackTrace();
	}

	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值