| Author |
exception problem:looking at following two code fragments!
|
Mellihoney Michael
Ranch Hand
Joined: Nov 27, 2002
Posts: 124
|
|
1. public class A { 2. private void method1() throws Exception { 3. throw new RuntimeException(); 4. } 6. public void method2() { 7. try { 8. method1(); 9. } catch(RuntimeException e) { 10. System.out.println("Caught Runtime Exception"); 11. } catch(Exception e) { 12. System.out.println("Caught Exception"); 13. } 14. } 15. public static void main(String args[]) { 16. A a = new A(); 17. a.method2(); 18. } 19. }//print "Caught Runtime Exception" -------------------COMPARE------------------------ public class B { private void method1() throws Exception { //throw new RuntimeException(); } public void method2() { try { method1(); } catch(RuntimeException e) { System.out.println("Caught Runtime Exception"); } catch(Exception e) { System.out.println("Caught Exception"); } } public static void main(String args[]) { B a = new B(); a.method2(); } }//compiled,no output?
|
a beginner in java
|
 |
Sridhar Srikanthan
Ranch Hand
Joined: Jan 08, 2003
Posts: 366
|
|
Mellihoney, declaring an exception in the throws clause does not make it to throw an exception. We use throws clause to warn any code that might call this method to be beware of any exception. Sri
|
 |
Mellihoney Michael
Ranch Hand
Joined: Nov 27, 2002
Posts: 124
|
|
to sri: just warning?How about the following code: public class B { private void method1(){ throw new RuntimeException(); } public void method2() { try { method1(); } catch(RuntimeException e) { System.out.println("Caught Runtime Exception"); } catch(Exception e) { System.out.println("Caught Exception"); } } public static void main(String args[]) { B a = new B(); a.method2(); } }// [ February 16, 2003: Message edited by: Mellihoney Michael ]
|
 |
Sridhar Srikanthan
Ranch Hand
Joined: Jan 08, 2003
Posts: 366
|
|
Originally posted by Mellihoney Michael: to sri: just warning?How are about the following code: public class B { private void method1(){ throw new RuntimeException(); } public void method2() { try { method1(); } catch( RuntimeException e) { System.out.println("Caught Runtime Exception"); } catch(Exception e) { System.out.println("Caught Exception"); } } public static void main(String args[]) { B a = new B(); a.method2(); } }//
RuntimeException is subclass of exception but it is not a checked exception. I guess you know the difference between a checked exception and a non-checked exception. A checked exception must declare that it throws the exception or must handle it in a try-catch block. A non-checked exception, on the other hand,does not need to either declare or throw exceptions. A good tutorial for exceptions is at this place Hope this helps Sri
|
 |
Mellihoney Michael
Ranch Hand
Joined: Nov 27, 2002
Posts: 124
|
|
|
thanks!
|
 |
 |
|
|
subject: exception problem:looking at following two code fragments!
|
|
|