java中的异常处理分为两步
1.抛出异常
2.捕获异常
首先,我们要在类中声明可能存在异常的地方,再在调用main函数时,捕获可能抛出的异常。
抛出异常:throw new Exception ("e"); e=异常名称;
捕获异常:try{},catch{}
实现代码:
public class Converter
{
public int String2int(String s) throws Exception
{
if (s.length()>11)
throw new Exception ("超出范围");
int result =0;
for (int i =0; i<s.length(); i++)
{
char ch = s.charAt(i);
if (! isValid(ch))
throw new Exception("非法字符");
result = 10* result +(ch - '0');
}
return result;
}
private boolean isValid(char ch)
{
if (ch >= '0' && ch <='9') return true;
if(ch =='-') return true;
return false;
}
public class Example
{
public static void main(String[] args)
{
Converter conv = new Converter();
try
{
int result = conv.String2int("123");
System.out.println(result);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("exit");
}
}