Java异常机制

Java异常机制##

捕获异常

(1)catch
(2)finally
(3)catch-finally

声明异常

(1)throws(Expection类型 Checked Exception类型)
(2)try-catch-finally

throw&throws

(1)throws用于声明方法可能产生的异常类型
(2)throw手动抛出异常对象
(3)throws写在方法名称后面
(4)throw写在方法里

import java.util.Scanner;
public class test {
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		try {
		System.out.println("输入被除数");
		int numA=input.nextInt();
		System.out.println("输入除数");
		int numB=input.nextInt();
		int result= numA/numB;
		System.out.println(numA+"/"+numB+"="+result);
		}
		/*异常一号catch(Exception e) {
			e.printStackTrace();
		}*/
		/*异常二号finally {
			System.out.println("......");
		}*/
		catch(ArithmeticException e) {
			System.err.println(",,,,,");
			System.out.println("    "+e.getMessage());
			return ;
		}finally {
			System.out.println("finally中的代码");
		}	
	}
}

自定义异常

public class CustomException extends Exception {

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

	public CustomException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}
	
}
import java.util.Scanner;

public class testCustomException {
	public static void main(String [] args) throws CustomException {
		Scanner input=new Scanner(System.in);
		System.out.println("请输入性别");
		String gender=input.next();
		if("男".equals(gender)||"女".equals(gender)) {
			System.out.println("正确");
		}else {
			throw new CustomException("错误");
		}
	}
}	

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值