Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is catch a method in java?

I have searched for some answers , but could not find & hence I am raising this as a new question. The catch method in the try-catch. Is it a method ? , Its taking an object of type Exception as an argument. But if its a method ,

  1. Who calls this method and by which object this method is called ?

  2. You cannot write a method definition inside another method definition normally.So if its a method , how am I able to write the catch inside another method ?

  3. If its not a method , then what is it ?

     public void foo() {
    
         try { ; 
    
         } catch (Exception ex) {
    
              ; // this is catch method body 
          }
    
    }
    

The above code means catch method body is inside another method foo()'s body.

like image 464
Tito Avatar asked Oct 11 '12 09:10

Tito


3 Answers

No, it's a special Java construct that denotes a block of code to be run if an Exception is caught, it's not a method. That block of code does take a parameter (of sorts), which is the exception to catch and then deal with - but this doesn't make it a method.

As pointed out in the comment, it's similar to, say, an if statement (you can view it as taking a "parameter" which is a boolean expression, but likewise this isn't a method either.)

like image 86
Michael Berry Avatar answered Sep 29 '22 08:09

Michael Berry


it's a language construct similar to if or while or for

like image 26
radalin Avatar answered Sep 29 '22 08:09

radalin


Who calls this method and by which object this method is called ?

The JVM executes it if the specified exception or a derived exception is thrown. No calling.

You cannot write a method definition inside another method definition normally.

You can't do it at all, except by writing an anonymous class, but that's another story.

So if it's a method

It isn't.

how am I able to write the catch inside another method ?

Because it isn't a method.

If it's not a method , then what is it ?

It's a language construct, just like try, do, while, for, switch, case, class, interface, ... are.

The above code means catch method body is inside another method foo()'s body.

No it doesn't, because it isn't a method.

Surely all these self-contradictions make it obvious that it isn't a method?

like image 22
user207421 Avatar answered Sep 29 '22 10:09

user207421