- It is possible to have try block without catch block by using finally block
- Java supports try with finally block
- As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
- We can place logic like connections closing or cleaning data in finally.
Java Program to write try without catch block | try with finally block
- package exceptionsInterviewQuestions;
- public class TryWithoutCatch {
- public static void main(String[] args) {
- try {
- System.out.println("inside try block");
- } finally{
- System.out.println("inside finally block");
- }
- }
- }
Output:
- inside try block
- inside finally block
- Finally block executes Even though the method have return type and try block returns something
Java Program to write try with finally block and try block returns some value
- package exceptionsInterviewQuestions;
- public class TryWithFinally {
- public static int method(){
- try {
- System.out.println("inside try block");
- return 10;
- } finally{
- System.out.println("inside finally block");
- }
- }
- public static void main(String[] args) {
- System.out.println(method());
- }
- }
Output:
- inside try block
- inside finally block
- 10
What happens if exception raised in try block?
- Even though exception raised in try block finally block executes.
very nice article....
ReplyDeleteCan we create constructor as a static
ReplyDeleteuse search box in website you will get answers . http://www.instanceofjava.com/2016/02/java-static-constructor-method.html
Delete