001 // Copyright 2007 by Basil Vandegriend. All rights reserved.
002
003 package com.basilv.examples.errorhandling;
004
005 import static org.junit.Assert.*;
006 import org.junit.Test;
007
008
009 public class ReturnInFinallyBlockTest
010 {
011
012 @SuppressWarnings("finally")
013 boolean performBusinessOperation() {
014 boolean operationResult = false;
015 try {
016
017 // Perform some business logic...
018 operationResult = true;
019
020 } catch (IllegalStateException e) {
021 // Handle this exception..
022 operationResult = false;
023 } catch (IllegalArgumentException e) {
024 // Handle this exception...
025 operationResult = false;
026 } finally {
027 // Common cleanup...
028
029 // Following line produces warning
030 // "Finally block does not complete normally"
031 return operationResult;
032 }
033 }
034
035
036 @SuppressWarnings("finally")
037 private boolean isReturnWithinFinally() {
038 try {
039 if (true) throw new RuntimeException();
040 } finally {
041 return true; // This hides the exception
042 }
043 }
044
045 private boolean isReturnOutsideFinally() {
046 try {
047 if (true) throw new RuntimeException();
048 } finally {
049 // Return outside finally block.
050 }
051 return true;
052 }
053
054 @Test
055 public void testReturnFromFinallyBlockWithUnhandledException() {
056
057 assertTrue(isReturnWithinFinally());
058 try {
059 isReturnOutsideFinally();
060 fail("Expect exception");
061 } catch (RuntimeException e) {
062 // Expected case.
063 }
064 }
065
066 }