Try catch and return in java

Return Statement in Try Catch Finally Block in Java

Scientech Easy

In the last tutorial, we have known about different cases of the control flow of try catch finally block in Java with the help of advanced example programs.

Now, two famous questions arise in the topic “try catch finally block” that

  1. Can we define return statement in try block or catch block or finally block in Java?
  2. If we return a value in try block or catch block or finally block, what will happen?

In this tutorial, we will learn all the different cases of try-catch-finally block with return statements.

Return Statement in Try Block only

Return statement in Java try catch finally block

Case 1 : Return statement in try block but do not have return statement at the end of method

Let’s take an example program where we will return a value in the try block but will not return a value at the end of method and see what error comes?

Program code 1:

package finallyProgram; public class TryReturnTest1 < int m1() // Compile time error. < try < System.out.println("I am in try block"); return 50; >catch(Exception e) < System.out.println("I am in catch block"); >// Here, no return statement at the end of method. > public static void main(String[] args) < TryReturnTest1 ft = new TryReturnTest1(); System.out.println(ft.m1()); >>

In the preceding program, we did not return a value at the end of the method. Therefore, we will get compile-time error: “This method must return a result of type int”. So, this is an invalid case.

Case 2 : Return statement in try block and end of method.

Let’s take an example program where we will return a value in the try block as well as at the end of method.

Program code 2:

package finallyProgram; public class TryReturnTest2 < int m1() < try < System.out.println("I am in try block"); return 50; >catch(Exception e) < System.out.println("I am in catch block"); >return 20; // return statement at the end of a method. > public static void main(String[] args) < TryReturnTest2 ft = new TryReturnTest2(); System.out.println(ft.m1()); >>
Output: I am in try block 50

This is a valid case because we have returned a value 20 at the end of method.

Case 3 : Return statement in try block and end of method but statement after return.

Let’s take an example program where we will write a statement after the return statement and see what happens?

Program code 4:

package finallyProgram; public class TryReturnTest3 < int m1() < try < System.out.println("I am in try block"); return 50; >catch(Exception e) < System.out.println("I am in catch block"); >return 20; System.out.println("Statement after return"); // Unreachable code. > public static void main(String[] args) < TryReturnTest3 ft = new TryReturnTest3(); System.out.println(ft.m1()); >>

When you will try to execute the preceding program, you will get an unreachable code error. This is because any statement after return statement will result in compile-time error stating “Unreachable code”.

Case 4 : Return statement in try block and at end of method but exception occurred in try block.

Let’s see the output of a program where an exception will occur in try block but returning a value in try block and at the end of method.

Program code 4:

package finallyProgram; public class TryReturnTest4 < int m1() < try < System.out.println("I am in try block"); int x = 10/0; return 50; >catch(ArithmeticException ae) < System.out.println("I am in catch block"); >return 20; > public static void main(String[] args) < TryReturnTest4 ft = new TryReturnTest4(); System.out.println(ft.m1()); >>
Output: I am in try block I am in catch block 20

In the preceding code, an exception occurred in a try block, and the control of execution is transferred to catch block to handle exception thrown by the try block.

Due to an exception occurred in try block, return statement in try block did not execute. Return statement defined at the end of method has returned a value 20 to the calling method.

Return Statement in Try-Catch block

Case 5 : Return statement in try-catch block.

Let’s take an example program in which we will declare a return statement inside try-catch block.

Program code 5:

package finallyProgram; public class TryCatchReturn1 < int m1() < try < System.out.println("I am in try block"); return 50; >catch(Exception e) < System.out.println("I am in catch block"); return 30; >> public static void main(String[] args) < TryCatchReturn1 obj = new TryCatchReturn1(); System.out.println(obj.m1()); >>
Output: I am in try block 50

Case 6 : Return statement in try-catch block and a statement at end of method.

Program code 6:

package finallyProgram; public class TryCatchReturn2 < int m1() < try < System.out.println("I am in try block"); return 50; // return statement inside try block. >catch(Exception e) < System.out.println("I am in catch block"); return 30; // return statement inside the catch block. >System.out.println("Method at end"); // Unreachable code. So, compile time error will occur. > public static void main(String[] args) < TryCatchReturn2 obj = new TryCatchReturn2(); System.out.println(obj.m1()); >>

Case 7 : Return statement in catch block but no exception in try block

Program code 7:

package finallyProgram; public class CatchReturn1 < int m1() < try < System.out.println("I am in try block"); >catch(Exception e) < System.out.println("I am in catch block"); return 30; // return statement inside the catch block. >return 100; // return statement at the end of method > public static void main(String[] args) < CatchReturn1 obj = new CatchReturn1(); System.out.println(obj.m1()); >>
Output: I am in try block 100

Case 8 : Return statement in catch block but exception occurred in try block.

Program code 8:

package finallyProgram; public class CatchReturn2 < int m1() < try < System.out.println("I am in try block"); int x = 20/0; System.out.println("Result: " +x); >catch(ArithmeticException ae) < System.out.println("I am in catch block"); return 30; >return 100; > public static void main(String[] args) < CatchReturn2 obj = new CatchReturn2(); System.out.println(obj.m1()); >>
Output: I am in try block I am in catch block 30

Return Statement in Try Catch Finally Block

Case 9 : Return statement in try block and finally block

Program code 9:

package finallyProgram; public class FinallyReturn1 < int m1() < try < System.out.println("I am in try block"); return 30; >finally < System.out.println("I am in finally block"); return 50; >> public static void main(String[] args) < FinallyReturn1 obj = new FinallyReturn1(); System.out.println(obj.m1()); >>
Output: I am in try block I am in finally block 50

In the preceding code, finally block overrides the value returned by try block. Therefore, this would return value 50 because the value returned by try has been overridden by finally block.

Case 10 : Return statement in catch and finally blocks

Program code 10:

package finallyProgram; public class FinallyReturn2 < @SuppressWarnings("finally") int m1() < try < System.out.println("I am in try block"); int x = 10/0; System.out.println("Result: " +x); >catch(ArithmeticException ae) < System.out.println("I am in catch block"); return 40; >finally < System.out.println("I am in finally block"); return 50; >> public static void main(String[] args) < FinallyReturn2 obj = new FinallyReturn2(); System.out.println(obj.m1()); >>
Output: I am in try block I am in catch block I am in finally block 50

In the above example program, finally block overrides the value returned by catch block. Therefore, the returned value is 50.

Case 11 : Return statement in catch and finally blocks but a statement after finally block

Program code 11:

package finallyProgram; public class FinallyReturn3 < @SuppressWarnings("finally") int m1() < int a = 20, b = 0; try < System.out.println("I am in try block"); int c = a/b; System.out.println("Result: " +c); >catch(ArithmeticException ae) < System.out.println("I am in catch block"); return 40; >finally < System.out.println("I am in finally block"); return 50; >System.out.println("Statement after finally block"); > public static void main(String[] args) < FinallyReturn3 obj = new FinallyReturn3(); System.out.println(obj.m1()); >>
Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code

In this tutorial, we have covered different cases of return statement in try-catch and finally blocks in Java with the help of various case examples. Hope that you will have understood all the basic cases and practiced example programs.
Thanks for reading.

Источник

Обработка исключений Java: try-catch-finally

В предыдущих уроках я рассмотрел блок try-catch и вложенный блок try. В этом руководстве мы увидим блок finally, который используется вместе с try-catch. Он содержит все важные операторы, которые должны быть выполнены независимо от того, происходит ли исключение.

Синтаксис

Простой пример

Здесь вы можете видеть, что исключение произошло в блоке try, который был обработан в блоке catch, после того, как этот блок finally был выполнен.

class Example < public static void main(String args[]) < try< int num=121/0; System.out.println(num); >catch(ArithmeticException e) < System.out.println("Number should not be divided by zero"); >/* Finally block will always execute * even if there is no exception in try block */ finally < System.out.println("This is finally block"); >System.out.println("Out of try-catch-finally"); > >
Number should not be divided by zero This is finally block Out of try-catch-finally

Несколько важных моментов

  1. Блок finally должен быть связан с блоком try, нельзя использовать его без try. Вы должны поместить в этот блок те операторы, которые должны выполняться всегда.
  2. Блок finally не является обязательным, как мы видели в предыдущих уроках. Try-catch достаточен для обработки исключений, однако, если вы поместите finally, он всегда будет выполняться после выполнения try.
  3. В нормальном случае, когда в блоке try нет исключения, тогда блок finally выполняется после блока try. Однако, если возникает, catch выполняется перед finally.
  4. Исключение в блоке finally работает точно так же, как и любое другое.
  5. Операторы, присутствующие в блоке finally, выполняются, даже если try содержит операторы передачи управления, такие как return, break или continue.

Пример с оператором return

Хотя у нас есть метод return, блок finally все равно выполняется.

class JavaFinally < public static void main(String args[]) < System.out.println(JavaFinally.myMethod()); >public static int myMethod() < try < return 112; >finally < System.out.println("This is Finally block"); System.out.println("Finally block ran even after return statement"); >> >
This is Finally block Finally block ran even after return statement 112

Случаи, когда не выполняется

Обстоятельствами, препятствующими выполнению кода в блоке finally, являются:

  • окончание потока;
  • использование системой метода exit();
  • исключение, возникающее в блоке finally.

Оператор close()

Оператор close() используется для закрытия всех открытых потоков в программе. Хорошей практикой является использование внутри блока finally. Поскольку блок выполняется, даже если возникает исключение, вы можете быть уверены, что все входные и выходные потоки закрыты должным образом независимо от того, возникло исключение или нет.

. try < OutputStream osf = new FileOutputStream( "filename" ); OutputStream osb = new BufferedOutputStream(opf); ObjectOutput op = new ObjectOutputStream(osb); try< output.writeObject(writableObject); >finally < op.close(); >> catch(IOException e1) < System.out.println(e1); >.

Без блока catch

Блок try-finally возможен без блока catch.

. InputStream input = null; try < input = new FileInputStream("inputfile.txt"); >finally < if(input != null) < try < in.close(); >catch(IOException exp) < System.out.println(exp); >> > .

System.exit()

Оператор System.exit() ведет себя иначе, чем оператор return. Всякий раз, когда он вызывается в блоке try, finally не выполняется:

. try < //try block System.out.println("Inside try block"); System.exit(0) >catch(Exception exp) < System.out.println(exp); >finally < System.out.println("Java finally block"); >.

В приведенном выше примере, если System.exit(0) вызывается без каких-либо исключений, то, finally, не будет выполняться. Однако если при его вызове произойдет какое-либо исключение, будет выполнен блок finally.

Блок try-catch-finally

  • Либо оператор try должен быть связан с блоком catch, либо с finally.
  • Так как catch выполняет обработку исключений и finally выполняет очистку, лучший способ – использовать оба из них.

Примеры

Пример 1 : Демонстрируется работа блока finally, когда в блоке try не возникает исключение

class Example1 < public static void main(String args[])< try< System.out.println("First statement of try block"); int num=45/3; System.out.println(num); >catch(ArrayIndexOutOfBoundsException e) < System.out.println("ArrayIndexOutOfBoundsException"); >finally < System.out.println("finally block"); >System.out.println("Out of try-catch-finally block"); > >
First statement of try block 15 finally block Out of try-catch-finally block

Пример 2 : Показана работа блока finally, когда исключение не обрабатывается в блоке catch:

class Example2 < public static void main(String args[])< try< System.out.println("First statement of try block"); int num=45/0; System.out.println(num); >catch(ArrayIndexOutOfBoundsException e) < System.out.println("ArrayIndexOutOfBoundsException"); >finally < System.out.println("finally block"); >System.out.println("Out of try-catch-finally block"); > >
First statement of try block finally block Exception in thread "main" java.lang.ArithmeticException: / by zero at beginnersbook.com.Example2.main(Details.java:6)

Как видно, система сгенерировала сообщение об исключении, но перед этим успешно завершился блок finally.

Пример 3 : Когда исключение возникает в блоке try и обрабатывается должным образом в блоке catch:

class Example3 < public static void main(String args[])< try< System.out.println("First statement of try block"); int num=45/0; System.out.println(num); >catch(ArithmeticException e) < System.out.println("ArithmeticException"); >finally < System.out.println("finally block"); >System.out.println("Out of try-catch-finally block"); > >
First statement of try block ArithmeticException finally block Out of try-catch-finally block

Источник

Читайте также:  Пример работы CSS
Оцените статью