Can we have try without catch block in java

Yes,  we can have try without catch block by using finally block.
You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit().

Lets understand with the help of example.
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  try
  {
   System.out.println("Executing try block"); 
  }
  finally
  {
   System.out.println("Executing finally block"); 
  }
 }
}

When you execute above program, you will get following output:
Executing try block
Executing finally block

What happens when you have return statement in try block:

If you have return statement in try block, still finally block executes.
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static String print()
 {
  try
  {
   System.out.println("Executing try block"); 
   return "Return from try block";
  }
  finally
  {
   System.out.println("Executing finally block"); 
  }
 }
}


When you execute above program, you will get following output:
Executing try block
Executing finally block
Return from try block

What happens if you have return statement in finally block too: 

It overrides whatever is returned by try block. Lets understand with the help of example:
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static String print()
 {
  try
  {
   System.out.println("Executing try block"); 
   return "Return from try block";
  }
  finally
  {
   System.out.println("Executing finally block"); 
   return "Return from finally block";
  }
 }
}

When you execute above program, you will get following output:
Executing try block
Executing finally block
Return from finally block

What if exception is thrown in try block :

If exception is thrown in try block, still finally block executes.
package org.arpit.java2blog;

public class TryWithoutCatchMain {

 public static void main(String args[])
 {
  System.out.println(print());
 }
 
 public static int  print()
 {
  try
  {
   throw new NullPointerException();
   
  }
  finally
  {
   System.out.println("Executing finally block"); 
   
  }
 }
}


When you execute above program, you will get following output:
Executing finally block
Exception in thread "main" java.lang.NullPointerException
 at org.arpit.java2blog.TryWithoutCatchMain.print(TryWithoutCatchMain.java:14)
 at org.arpit.java2blog.TryWithoutCatchMain.main(TryWithoutCatchMain.java:7)

You can go through top 50 core java interview questions for more such questions.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012