System.out.println("one finally"); return new String("finally return");
} } class myException extends Exception { public myException(String msg) { super(msg); } }
楼主你的程序简直太.......................错误太多了!首先是拼写错误!--------楼上有位大哥给你指出来了! 其次:是逻辑错误!------不知道怎么说!反正就是.................写的乱!楼主看看我帮你写的吧!我上面这个程序是自定义了一个异常! 思路很清晰,如果楼主不想自定义异常的话请看下面的程序 public class test { public static void main(String[] args) {
改成
public static String testFinallay(){
Finally子句是无法被编译的!
@.@||~
public static String testFinallay()throws Exception{testFinallay()
test.testFinally()); 你看这两个 是多了点东西 哈哈 多了个a ~~~~~~~
{
public static void main(String[] args)
{
try
{
System.out.println(test.testFinallay("admi"));
}
catch(myException e)
{
System.out.println("main test");
}
}
public static String testFinallay(String username)throws myException
{
if(username.equals("admin"))
{
throw new myException("try");
}
System.out.println("one finally");
return new String("finally return");
}
}
class myException extends Exception
{
public myException(String msg)
{
super(msg);
}
}
其次:是逻辑错误!------不知道怎么说!反正就是.................写的乱!楼主看看我帮你写的吧!我上面这个程序是自定义了一个异常!
思路很清晰,如果楼主不想自定义异常的话请看下面的程序
public class test
{
public static void main(String[] args)
{
try
{
System.out.println(test.testFinallay("admin"));
}
catch(Exception e)
{
System.out.println("main test");
}
}
public static String testFinallay(String username)throws Exception
{
if(username.equals("admin"))
{
throw new Exception("try");
}
System.out.println("one finally");
return new String("finally return");
}
}
你的意思是:如果你的testFinallay方法出现异常,就执行System.out.println("main test");
如果没有异常就执行System.out.println("one finally");
return new String("finally return");
但是首先你要注意的是:既然你为你的testFinallay方法抛出了异常,那你在你的方法里就不需要捕捉了,你完全可以在你的测试函数中捕捉就象你所想的那样用System.out.println("main test");
其次,你要注意,要想捕捉到异常,那你就必须为你的方法设定一个异常,因为你的方法其实没有什么异常,只不过是抛出异常罢了!如果不设定的话,就永远不会有异常,因此就不会执行System.out.println("main test");
不一定
catch中也常抛出异常
有点不妥吧,有些时候我们要捕获原异常来抛出另外一种异常,这也可能。
比如:
try {
//关于数据库的连接和操作
...
}
catch(SQLException ex) {
throw new MyException(myMessage+"\n"+ex.getMessage());
}
...