public class Test01 { public static void main(String[] args) { System.out.println("请输入1~3之间任一数字:"); Scanner in = new Scanner(System.in); try { int num = in.nextInt(); switch (num) { case 1: System.out.println("C#编程"); break; case 2: System.out.println("JAVA编程"); break; case 3: System.out.println("编程专业英语"); break; } } catch (Exception e) { System.out.println("输入值不是数字"); e.printStackTrace(); } finally { System.out.println("欢迎提出建议!"); } } }
请输入1~3之间任一数字: d 输入值不是数字 java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at Test2019.M02.d19.Test01.main(Test01.java:10) 欢迎提出建议!
定义报错的类:AgeException
public class AgeException{ private int age; public void setAge(int age) throws Exception{ if(age >=1 && age<=100){ this.age = age; }else{ throw new Exception("年龄必须在1到100之间!"); } } }
测试:
public class Test02 { public static void main(String[] args) { AgeException person = new AgeException(); try { person.setAge(120); } catch (Exception e) { e.printStackTrace(); } } }
java.lang.Exception: 年龄必须在1到100之间! at Test2019.M02.d19.AgeException.setAge(AgeException.java:12) at Test2019.M02.d19.Test02.main(Test02.java:8)
自己定义异常
public class GenderException extends Exception{ //好处:可以通过异常名字,清晰知道异常原因,以及针对处理 //无参构造方法 public GenderException() { super(); } //有参构造方法,只有继承Exception的构造方法,才能在控制台输出,错误信息 public GenderException(String message) { super(message); }
public class GenderDamo { private String sex; public void setSex(String sex)throws GenderException{ if(sex == "男"){ System.out.println("他是男生!"); }else if (sex == "女"){ System.out.println("她是女生!"); }else{ throw new GenderException("必须输入:男or女"); } } public static void main(String[] args) { GenderDamo person = new GenderDamo(); try { person.setSex("Gay"); } catch (GenderException e) { e.printStackTrace(); } } }