What is the difference between throws with a method name and an exception catch?

I am very new to exception handling in java, so this question may seem silly, but please let it answer. Suppose I have a method A in which part of the code can throw an exception B , then what is the difference between catching an exception in a method or writing a method declaration as: -

void A() throws B{
     ----//----
     }
+5
source share
9 answers

The difference lies in the method call.

  • throws Exception, , , Exception [ catch], [ throws ].

  • catch Exception, Exception , , , Exception.

:

  • , Exception, catch .

  • Exception, catch, .

. catch a Exception [ ]. Exception , . .

. , , - throws Exception. StackTrace . : " ?" , , , , .

+9

A(), A(), , , ..

() , / , A(), .

+2

, B , . , , Java. throws , , B , , .

+2

, , - , , . , .

, try/catch : try, , , .

A , ; A , A , .

+2

, "" .

, "" try-catch .

try {
//Do your stuff here
}

catch (Exception ex) {
System.out.println("I just caught exception = " + ex);
}
+1

, , , , .

, , .

.

+1

, ( ), ( ) ; , , , , , , .

+1

, , - . , A() B, , A() B. , - A(), , B .

+1
  • : . , - try- , catch, .

  • Throwing Exception: . , , , , . , :

method1()   {
x.method2();
  }
  method2() {   
   method3(); 
  }  
method3() throws SomeException   {  .....  ......   }

Then, if the code in method3 throws SomeException, it will be passed to method2, if method2 also does not handle the exception, and then method1, also in the method stack.

+1
source

All Articles