定义三种新的异常类型。写一个类,在一个方法中抛出这三种异常。在main()里调用这个方法,仅用一个catch子句捕获
这三种异常.class A extends Exception{}
class B extends Exception{}
class C extends Exception{}public class Exception9 {
static void f() throws A,B,C{
throw new A();
// throw new B(): 这里不能同时抛出哦!
//throw new C();
}
public static void main(String[] args){
try{
f();;
}
catch(Exception e){
e.printStackTrace(System.out);
}
}
}
按照我的方法不可以啊,请问大家该怎么做呢?
这三种异常.class A extends Exception{}
class B extends Exception{}
class C extends Exception{}public class Exception9 {
static void f() throws A,B,C{
throw new A();
// throw new B(): 这里不能同时抛出哦!
//throw new C();
}
public static void main(String[] args){
try{
f();;
}
catch(Exception e){
e.printStackTrace(System.out);
}
}
}
按照我的方法不可以啊,请问大家该怎么做呢?
throw new B(): 这里不能同时抛出哦!
//throw new C();
你第一个抛出A,这个代码后面的代码都是不可达的了,编译器不允许这样。static void f() throws A,B,C
这里只是说明有可能抛出这几种异常中的某个。
不可能都抛出,因为你抛出一个异常之后方法就结束了,没有时机去抛出别的异常。
这三种异常.
那这道题该怎么完成?
可以不可以同时捕获3个异常?
class A extends ExBase {}
class B extends ExBase {}
class C extends ExBase {}class Thrower {
void f() throws A, B, C {
throw new A();
}
}public class Exception9 {
public static void main(String args[]) {
Thrower t = new Thrower();
try {
t.f();
} catch(ExBase e)
{
System.out.println("caught " + e);
}
}
}
package chapter9;public class MatchingExceptions
{ /**
* @param args
*/
private void putexception() throws MyException11,MyException12,MyException13
{
try
{
throw new MyException11();
}
catch(MyException11 ex1)
{
ex1.printStackTrace(System.out);
try{
throw new MyException12();
}
catch(MyException12 ex2)
{
ex2.printStackTrace(System.out);
throw new MyException13();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
MatchingExceptions met=new MatchingExceptions();
met.putexception();
}
catch(Exception ex3)
{
ex3.printStackTrace(System.out);
}
// finally
// {
// return;
//
// }
}}
class MyException11 extends Exception
{
}class MyException12 extends Exception
{
}class MyException13 extends Exception
{
}