需求是这个样子的:
代码如下:
package com.hidata.devops.paas.demo; import java.util.Scanner; /** * 任务4、自定义异常 输出 */ public class MyException extends Exception{ public MyException(String message) { super(message); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入任意一个字符串:"); String str = scanner.next(); try { if(str.length() > 5){ throw new MyException("The string is too long"); } }catch (MyException e){ System.out.println(e.getMessage()); } } }
运行结果:
请输入任意一个字符串: 214124123 The string is too long Process finished with exit code 0