日期:2014-05-20  浏览次数:20852 次

throw Exception 的简单问题
class   Test{
        public   void   throwException(){
                  throw   new   Exception( "aaa ");
        }
}
Main.java:18:   未报告的异常   java.lang.Exception;必须对其进行捕捉或声明以便抛出

怎么样才能抛出去呢?
    try
                {
                  throw   new   Exception( "aaa ");
                }catch(Exception   e)
                {
                        throw   e;
                }
也不行!

------解决方案--------------------
class Test{
public void throwException()throws Exception{
throw new Exception( "aaa ");
}
}

------解决方案--------------------
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;


public class Tester {

/**
* @param args
*/
public static void main(String[] args) {
int a,b;
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));

try {
System.out.print( "a: ");
a=Integer.parseInt(reader.readLine());
System.out.print( "b: ");
b=Integer.parseInt(reader.readLine());
System.out.println( "result= "+ new Divider().perform(a, b));
} catch (NumberFormatException e) {
System.out.println( "NumberFormatException found, msg: "+e.getMessage());
} catch (IOException e) {
System.out.println( "IOException found, msg: "+e.getMessage());
} catch (MyException e) {
System.out.println( "MyException found, msg: "+e.getMessage());
} catch(ArithmeticException e){
System.out.println( "ArithmeticException found, msg: "+e.getMessage());
}

System.out.println( "process end.. ");


}

}


class Divider {
Float perform(int a, int b) throws ArithmeticException,MyException{
Float result=null;
if(a==12)
throw new MyException( "12 is not a right number! ");
result=(float)(a/b);
return result;
}
}

public class MyException extends Exception {

public MyException(String message)
{
super(message);
}

}


关于异常的常用几种写法。