异常throw new Exception相关代码

来源:互联网 发布:剑网三有mac版吗 编辑:程序博客网 时间:2024/05/18 02:26
<span style="font-size:18px;">package com.yunhe.xiawu;//自己设置抛出异常信息public class YiChangDemo {char sex;public void setSex(char sex) throws Exception {if ('男' == sex && '女' == sex) {this.sex = sex;} else {// 除了系统可以抛出异常,自己也可以设置抛出异常throw new Exception("你输入的不对,只能输入男和女");}}public static void main(String[] args) {try {// 假设用户输入性别时输入 bnew YiChangDemo().setSex('b');} catch (Exception e) {System.out.println("输入错误");// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("程序结束");}}</span>
package com.yunhe.xiawu;import java.util.Scanner;public class YiChang {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int res = 0, num1 = 0, num2 = 0;System.out.println("input num1");if (scanner.hasNextInt()) {num1 = scanner.nextInt();}System.out.println("input num2");if (scanner.hasNextInt()) {num2 = scanner.nextInt();}try {res = num1 / num2;} catch (Exception e) {System.out.println("除数不能为0");// TODO Auto-generated catch blocke.printStackTrace();} finally {System.out.println("不管程序报错不报错,finally里的程序都会执行");}System.out.println(res);}}


0 0
原创粉丝点击