java中如何一次抛出多个异常

Python020

java中如何一次抛出多个异常,第1张

基本思路就是定义三个类,继承异常的父类,然后在需要抛出异常的地方,throws一下就可以了,示例如下:

public class CatchMultiException {

 

    public static void main(String[] args) throws Exception {

        try {

            test(2)

        } catch (Exception e) {

            if (e instanceof TestAException || e instanceof TestBException

                    || e instanceof TestCException) {

                e.printStackTrace()

            } else {

                throw e

            }

        }

    }

 

    public static void test(int a) throws TestAException, TestBException,

            TestCException {

        if (a == 0) {

            throw new TestAException()//抛出第一个异常

        }

        if (a == 1) {

            throw new TestBException()//抛出第二个异常

        }

        if (a == 2) {

            throw new TestCException()//抛出第三个异常

        }

    }

}

 

class TestAException extends Exception {//继承父类Exception

    private static final long serialVersionUID = 1L

}

 

class TestBException extends Exception {

    private static final long serialVersionUID = 1L

}

 

class TestCException extends Exception {

    private static final long serialVersionUID = 1L

}

//例子

import java.util.Random

public class Test

{

public static void main(String[] args)

{

final Random r=new Random()

final Exception[] exs=

{

new Exception1(),

new Exception2(),

new Exception("Exception")

}

for(int i=0i<5i++)

{

try

{

throw exs[r.nextInt(exs.length)]

}

catch(Exception1 ex)

{

System.out.println(ex)

}

catch(Exception2 ex)

{

System.out.println(ex)

}

catch(Exception ex)

{

System.out.println(ex)

}

}

}

}

class Exception1 extends Exception

{

@Override

public String toString()

{

return "Exception1"

}

}

class Exception2 extends Exception

{

@Override

public String toString()

{

return "Exception2"

}

}

//例子二(需较新的java版本才能支持)

import java.util.Random

public class Test

{

public static void main(String[] args)

{

final Random r=new Random()

final Exception[] exs=

{

new Exception1(),

new Exception3(),

new Exception2(),

new Exception("Exception")

}

for(int i=0i<5i++)

{

try

{

throw exs[r.nextInt(exs.length)]

}

catch(Exception3|Exception1|Exception2 ex)

{

System.out.println(ex)

}

catch(Exception ex)

{

System.out.println(ex)

}

}

}

}

class Exception1 extends Exception

{

@Override

public String toString()

{

return "Exception1"

}

}

class Exception2 extends Exception

{

@Override

public String toString()

{

return "Exception2"

}

}

class Exception3 extends Exception

{

@Override

public String toString()

{

return "Exception3"

}

}