package hello; //自定义异常 class MathException extends Exception{ MathException(){ System.out.println("输入的格式不正确!"); } } public class Hello{ public static void input(String t) throws MathException //抛出异常选项 { int i; char[]stringArr=t.toCharArray(); //将自字符串放进数组 for(i=0;i<t.length();i++) { //通过数组遍历,检验字符串是否由纯数组组成 if(stringArr[i]<49||stringArr[i]>57) { throw new MathException(); //抛出异常 } } System.out.println(String.valueOf(t)); } public static void main(String args[]) { try { String t=new String("123123"); input(t); } catch(MathException e) { System.out.println(e); } finally { System.out.println("程序运行结束!"); } } }
原文:https://www.cnblogs.com/zhulmz/p/11486745.html