• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try {} catch() {} finally {}

 
Andrey Opanasets
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of these statements are true. Select all correct answers.

1. For each try block there must be at least one catch block defined.

2. A try block may be followed by any number of finally blocks.

3. A try block must be followed by at least one finally or catch block.

4. If both catch and finally blocks are defined, catch block must precede the finally block

My answer id 4. But test says that the answer 2 is also correct. Why? This code is not compliled:

try{

int i=0;

int j=1/i;

} catch(Exception e) {

} finally {

System.out.println(1);

} finally {

System.out.println(2);

}

How can I defined two or more finally blocks?
Thanx to all.
 
Vikrama Sanjeeva
Ranch Hand
Posts: 756
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I AM WITH U... A/C to me option 2 is NOT Correct!
BTW Which test u r using.
Bye.
Viki.

------------------
Count the flowers of ur garden,NOT the leafs which falls away!
 
Andrey Opanasets
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry. Test say 3 and 4.
Can you lock this topic.
 
vinay jain
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Answers should be 3 and 4, since a try block can not stand on its own e.g. If you have
<pre>
try {
// do something
}
...
</pre>
and there is no catch or finally block then it is an error.
 
Madan, Gopal
Ranch Hand
Posts: 86
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody explain why option 1 is not true!!??
1. For each try block there must be at least one catch block defined.

I thought this is valid!!

[This message has been edited by Madan, Gopal (edited November 07, 2001).]
 
Salamina Daniel
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is obvious, Madan.
You can have a try - finally block whitout any catch involved and Java Language Specification -14.19 gives this description
TryStatement:
try Block Catches
try Block Catches-opt! Finally
So, as you can see the catch block is optional !
Example:
import java.io.*;
public class ATest{
public static void main(String arg[]) throws IOException{
try{
FileInputStream f=new FileInputStream("c:\test.txt");
}
finally{
System.out.println("No catch block");
}
}
}
Therefore answer 1.(For each try block there must be at least one catch block defined.) is wrong !
Best regards

[This message has been edited by Salamina Daniel (edited November 07, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic