{
int len,i,ans=0;
boolean flag=true;
len=s.length();
for (i=0;i<=len-1;i++)
{
if (s.charAt(i)<'0'||s.charAt(i)>'9')
{
flag=false;
break;
}
}
if (s.length()>=6)
{
throw new TooLong();//遇到异常抛出
}
else if (s.length()==0)
{
throw new ZeroLength();
}
else if (flag==false)
{
throw new InvalidChar();
}
for (i=0;i<=len-1;i++)
{
ans=ans+(s.charAt(i)-'0')*((int)Math.pow(10,len-i-1));
}
return ans;
}
本题完整代码如下:
异常类型有:空字符,超过长度字符串和含有非法字符的字符串。
import java.util.*;
class InvalidChar extends Exception
{
public InvalidChar()
{
super("字符串中含有非法字符,无法转换为整型");
}
}
class TooLong extends Exception
{
public TooLong()
{
super("字符串长度过长,无法转换成整型");
}
}
class ZeroLength extends Exception
{
public ZeroLength()
{
super("长度是零,无法转换成整型");
}
}
public class ExceptionTester
{
public static int StringtoInt(String s) throws TooLong,ZeroLength,InvalidChar
{
int len,i,ans=0;
boolean flag=true;
len=s.length();
for (i=0;i<=len-1;i++)
{
if (s.charAt(i)<'0'||s.charAt(i)>'9')
{
flag=false;
break;
}
}
if (s.length()>=6)
{
throw new TooLong();
}
else if (s.length()==0)
{
throw new ZeroLength();
}
else if (flag==false)
{
throw new InvalidChar();
}
for (i=0;i<=len-1;i++)
{
ans=ans+(s.charAt(i)-'0')*((int)Math.pow(10,len-i-1));
}
return ans;
}
public static void main(String args[])
{
int a;
String s;
Scanner cin=new Scanner(System.in);
System.out.println("输入一个字符串");
s=cin.nextLine();
try
{
a=StringtoInt(s);
}
catch(Exception e)
{
System.out.println(e.toString());
return;
}
System.out.println(a+"\n"+"没有异常被捕获");
return;
}
}
package com.cestbon.exception;
public class RpcException extends Exception {
/**
*
*/
private static final long serialVersionUID = 6554142484920002283L;
}