java二级-字符串转换整数并捕获异常

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("程序运行结束!");
	  }
	}
 }

 

posted @ 2019-09-08 15:53  翁德彪  阅读(736)  评论(0编辑  收藏  举报