Java Tutorial/Statement Control/throw

Материал из Java эксперт
Перейти к: навигация, поиск

Change Exception type and rethrow

   <source lang="java">

class MyException extends Exception {

 MyException() {
   super("My Exception");
 }

} class YourException extends Exception {

 YourException() {
   super("Your Exception");
 }

} class ChainDemo {

 public static void main(String[] args) {
   try {
     someMethod1();
   } catch (MyException e) {
     e.printStackTrace();
   }
 }
 static void someMethod1() throws MyException {
   try {
     someMethod2();
   } catch (YourException e) {
     System.out.println(e.getMessage());
     MyException e2 = new MyException();
     e2.initCause(e);
     throw e2;
   }
 }
 static void someMethod2() throws YourException {
   throw new YourException();
 }

}</source>





Demonstrate throw.

   <source lang="java">

class ThrowDemo {

 static void demoproc() {
   try {
     throw new NullPointerException("demo");
   } catch (NullPointerException e) {
     System.out.println("Caught inside demoproc.");
     throw e; // rethrow the exception
   }
 }
 public static void main(String args[]) {
   try {
     demoproc();
   } catch (NullPointerException e) {
     System.out.println("Recaught: " + e);
   }
 }

}</source>