Unreachable code, but reachable with exception
This code is part of an application that reads from and writes to an ODBC connected database. It creates a record in the database and then checks if a record has been successfully created, then returning true.
My understanding of control flow is as follows:
command.ExecuteNonQuery() is documented to throw an InvalidOperationException when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of the try block would stop, the finally block would be executed, then would execute the return false; at the bottom.
However, my IDE claims that the return false; is unreachable code. And it seems to be true, I can remove it and it compiles without any complaints. However, for me it looks as if there would be no return value for the code path where the mentioned exception is thrown.
private static bool createRecord(String table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
} finally {
command.Dispose();
}
return false;
}
What is my error of understanding here?
c# exception unreachable-code
add a comment |
This code is part of an application that reads from and writes to an ODBC connected database. It creates a record in the database and then checks if a record has been successfully created, then returning true.
My understanding of control flow is as follows:
command.ExecuteNonQuery() is documented to throw an InvalidOperationException when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of the try block would stop, the finally block would be executed, then would execute the return false; at the bottom.
However, my IDE claims that the return false; is unreachable code. And it seems to be true, I can remove it and it compiles without any complaints. However, for me it looks as if there would be no return value for the code path where the mentioned exception is thrown.
private static bool createRecord(String table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
} finally {
command.Dispose();
}
return false;
}
What is my error of understanding here?
c# exception unreachable-code
1
docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
– Anton Z
12 hours ago
24
Side note: do not callDisposeexplicitly, but putusing:using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }
– Dmitry Bychenko
12 hours ago
add a comment |
This code is part of an application that reads from and writes to an ODBC connected database. It creates a record in the database and then checks if a record has been successfully created, then returning true.
My understanding of control flow is as follows:
command.ExecuteNonQuery() is documented to throw an InvalidOperationException when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of the try block would stop, the finally block would be executed, then would execute the return false; at the bottom.
However, my IDE claims that the return false; is unreachable code. And it seems to be true, I can remove it and it compiles without any complaints. However, for me it looks as if there would be no return value for the code path where the mentioned exception is thrown.
private static bool createRecord(String table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
} finally {
command.Dispose();
}
return false;
}
What is my error of understanding here?
c# exception unreachable-code
This code is part of an application that reads from and writes to an ODBC connected database. It creates a record in the database and then checks if a record has been successfully created, then returning true.
My understanding of control flow is as follows:
command.ExecuteNonQuery() is documented to throw an InvalidOperationException when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of the try block would stop, the finally block would be executed, then would execute the return false; at the bottom.
However, my IDE claims that the return false; is unreachable code. And it seems to be true, I can remove it and it compiles without any complaints. However, for me it looks as if there would be no return value for the code path where the mentioned exception is thrown.
private static bool createRecord(String table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
} finally {
command.Dispose();
}
return false;
}
What is my error of understanding here?
c# exception unreachable-code
c# exception unreachable-code
edited 12 hours ago
Dmitry Bychenko
109k1094135
109k1094135
asked 12 hours ago
0xCAFEBABE0xCAFEBABE
3,69432553
3,69432553
1
docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
– Anton Z
12 hours ago
24
Side note: do not callDisposeexplicitly, but putusing:using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }
– Dmitry Bychenko
12 hours ago
add a comment |
1
docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
– Anton Z
12 hours ago
24
Side note: do not callDisposeexplicitly, but putusing:using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }
– Dmitry Bychenko
12 hours ago
1
1
docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
– Anton Z
12 hours ago
docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
– Anton Z
12 hours ago
24
24
Side note: do not call
Dispose explicitly, but put using: using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }– Dmitry Bychenko
12 hours ago
Side note: do not call
Dispose explicitly, but put using: using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }– Dmitry Bychenko
12 hours ago
add a comment |
7 Answers
7
active
oldest
votes
The finally may run on an Exception, though that aside it doesn't change the fact (in this case) it will still be an Uncaught Exception. Ergo, the last return will never get hit regardless.
If you want the code to continue onto the last return, Catch the Exception; If you don't, just leave it the way it is and remove the return
Example
try
{
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
}
catch(<some exception>)
{
// do something
}
finally
{
command.Dispose();
}
To be more clear from the documentation
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack. That
is, you can catch the exception in the method that calls the method
that contains the try-finally statement, or in the method that calls
that method, or in any method in the call stack. If the exception is
not caught, execution of the finally block depends on whether the
operating system chooses to trigger an exception unwind operation.
add a comment |
the finally block would be executed, then would execute the return false; at the bottom.
Wrong. finally doesn't swallow the exception. It honors it and the exception will be thrown as normal. It will only execute the code in the finally before the block ends (with or without an exception).
If you want the exception to be swallowed, you should use a catch block with no throw in it.
1
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
1
It does compile, but it will never hitreturn falsesince it will throw an exception instead @EhsanSajjad
– Patrick Hofman
12 hours ago
1
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
1
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
1
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
|
show 3 more comments
The warning is because you didn't use catch and your method is basically written like this:
bool SomeMethod()
{
return true;
return false; // CS0162 Unreachable code detected
}
Since you use finally solely to dispose, the preffered solution is to utilize using pattern:
using(var command = new WhateverCommand())
{
...
}
That's enough, to ensure what Dispose will be called. It's guaranteed to be called either after successful execution of code block or upon (before) some catch down in call stack (parent calls are down, right?).
If it wouldn't be about disposing, then
try { ...; return true; } // only one return
finally { ... }
is enough, since you will never have to return false at the end of method (there is no need for that line). Your method is either return result of command execution (true or false) or will throw an exception otherwise.
Consider also to throw own exceptions by wrapping expected exceptions (check out InvalidOperationException constructor):
try { ... }
catch(SomeExpectedException e)
{
throw new SomeBetterExceptionWithExplanaition("...", e);
}
This is typically used to say something more meaningful (useful) to the caller than nested call exception would be telling.
Most of times you don't really care about unhandled exceptions. Sometimes you need to ensure that finally is called even if exception is unhandled. In this case you simply catch it yourself and re-throw (see this answer):
try { ... }
catch { ...; throw; } // re-throw
finally { ... }
add a comment |
It seems, you are looking for something like this:
private static bool createRecord(string table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
// using: do not call Dispose() explicitly, but wrap IDisposable into using
using (var command = ...) {
try {
// Normal flow:
command.CommandText = sb.ToString();
// true if and only if exactly one record affected
return command.ExecuteNonQuery() == 1;
}
catch (DbException) {
// Exceptional flow (all database exceptions)
return false;
}
}
}
please, note, that finally doesn't swallow any exception
finally {
// this code will be executed; the exception will be efficently re-thrown
}
// and this code will never be reached
add a comment |
When the exception is thrown, the stack will unwind (execution will move out of the function) without returning a value, and any catch block in the stack frames above the function will catch the exception instead.
Hence, return false will never execute.
Try manually throwing an exception to understand the control flow:
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
// Try this.
throw new Exception("See where this goes.");
return returnValue == 1;
} finally {
command.Dispose();
}
add a comment |
On your code:
private static bool createRecord(String table, IDictionary<String,String> data, System.Data.IDbConnection conn, OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1; // You return here in case no exception is thrown
} finally {
command.Dispose(); //You don't have a catch so the exception is passed on if thrown
}
return false; // This is never executed because there was either one of the above two exit points of the method reached.
}
the finally block would be executed, then would execute the return false; at the bottom
This is the flaw in your logic because the finally block won't catch the exception and it will never reach the last return statement.
add a comment |
The last statement return false is unreachable, because the try block is missing a catch part that would handle the exception, so the exception is rethrown after the finally block and the execution never reaches the last statement.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55116849%2funreachable-code-but-reachable-with-exception%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
The finally may run on an Exception, though that aside it doesn't change the fact (in this case) it will still be an Uncaught Exception. Ergo, the last return will never get hit regardless.
If you want the code to continue onto the last return, Catch the Exception; If you don't, just leave it the way it is and remove the return
Example
try
{
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
}
catch(<some exception>)
{
// do something
}
finally
{
command.Dispose();
}
To be more clear from the documentation
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack. That
is, you can catch the exception in the method that calls the method
that contains the try-finally statement, or in the method that calls
that method, or in any method in the call stack. If the exception is
not caught, execution of the finally block depends on whether the
operating system chooses to trigger an exception unwind operation.
add a comment |
The finally may run on an Exception, though that aside it doesn't change the fact (in this case) it will still be an Uncaught Exception. Ergo, the last return will never get hit regardless.
If you want the code to continue onto the last return, Catch the Exception; If you don't, just leave it the way it is and remove the return
Example
try
{
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
}
catch(<some exception>)
{
// do something
}
finally
{
command.Dispose();
}
To be more clear from the documentation
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack. That
is, you can catch the exception in the method that calls the method
that contains the try-finally statement, or in the method that calls
that method, or in any method in the call stack. If the exception is
not caught, execution of the finally block depends on whether the
operating system chooses to trigger an exception unwind operation.
add a comment |
The finally may run on an Exception, though that aside it doesn't change the fact (in this case) it will still be an Uncaught Exception. Ergo, the last return will never get hit regardless.
If you want the code to continue onto the last return, Catch the Exception; If you don't, just leave it the way it is and remove the return
Example
try
{
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
}
catch(<some exception>)
{
// do something
}
finally
{
command.Dispose();
}
To be more clear from the documentation
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack. That
is, you can catch the exception in the method that calls the method
that contains the try-finally statement, or in the method that calls
that method, or in any method in the call stack. If the exception is
not caught, execution of the finally block depends on whether the
operating system chooses to trigger an exception unwind operation.
The finally may run on an Exception, though that aside it doesn't change the fact (in this case) it will still be an Uncaught Exception. Ergo, the last return will never get hit regardless.
If you want the code to continue onto the last return, Catch the Exception; If you don't, just leave it the way it is and remove the return
Example
try
{
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1;
}
catch(<some exception>)
{
// do something
}
finally
{
command.Dispose();
}
To be more clear from the documentation
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack. That
is, you can catch the exception in the method that calls the method
that contains the try-finally statement, or in the method that calls
that method, or in any method in the call stack. If the exception is
not caught, execution of the finally block depends on whether the
operating system chooses to trigger an exception unwind operation.
edited 1 hour ago
Lee Taylor
5,04472442
5,04472442
answered 12 hours ago
Michael RandallMichael Randall
34.1k73868
34.1k73868
add a comment |
add a comment |
the finally block would be executed, then would execute the return false; at the bottom.
Wrong. finally doesn't swallow the exception. It honors it and the exception will be thrown as normal. It will only execute the code in the finally before the block ends (with or without an exception).
If you want the exception to be swallowed, you should use a catch block with no throw in it.
1
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
1
It does compile, but it will never hitreturn falsesince it will throw an exception instead @EhsanSajjad
– Patrick Hofman
12 hours ago
1
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
1
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
1
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
|
show 3 more comments
the finally block would be executed, then would execute the return false; at the bottom.
Wrong. finally doesn't swallow the exception. It honors it and the exception will be thrown as normal. It will only execute the code in the finally before the block ends (with or without an exception).
If you want the exception to be swallowed, you should use a catch block with no throw in it.
1
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
1
It does compile, but it will never hitreturn falsesince it will throw an exception instead @EhsanSajjad
– Patrick Hofman
12 hours ago
1
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
1
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
1
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
|
show 3 more comments
the finally block would be executed, then would execute the return false; at the bottom.
Wrong. finally doesn't swallow the exception. It honors it and the exception will be thrown as normal. It will only execute the code in the finally before the block ends (with or without an exception).
If you want the exception to be swallowed, you should use a catch block with no throw in it.
the finally block would be executed, then would execute the return false; at the bottom.
Wrong. finally doesn't swallow the exception. It honors it and the exception will be thrown as normal. It will only execute the code in the finally before the block ends (with or without an exception).
If you want the exception to be swallowed, you should use a catch block with no throw in it.
answered 12 hours ago
Patrick HofmanPatrick Hofman
128k18175234
128k18175234
1
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
1
It does compile, but it will never hitreturn falsesince it will throw an exception instead @EhsanSajjad
– Patrick Hofman
12 hours ago
1
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
1
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
1
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
|
show 3 more comments
1
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
1
It does compile, but it will never hitreturn falsesince it will throw an exception instead @EhsanSajjad
– Patrick Hofman
12 hours ago
1
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
1
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
1
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
1
1
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
will the above sinppet compile in case exception, what will be returned?
– Ehsan Sajjad
12 hours ago
1
1
It does compile, but it will never hit
return false since it will throw an exception instead @EhsanSajjad– Patrick Hofman
12 hours ago
It does compile, but it will never hit
return false since it will throw an exception instead @EhsanSajjad– Patrick Hofman
12 hours ago
1
1
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
– Ehsan Sajjad
12 hours ago
1
1
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
– Patrick Hofman
12 hours ago
1
1
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
means it's just warning, but will build successfully right ?
– Ehsan Sajjad
12 hours ago
|
show 3 more comments
The warning is because you didn't use catch and your method is basically written like this:
bool SomeMethod()
{
return true;
return false; // CS0162 Unreachable code detected
}
Since you use finally solely to dispose, the preffered solution is to utilize using pattern:
using(var command = new WhateverCommand())
{
...
}
That's enough, to ensure what Dispose will be called. It's guaranteed to be called either after successful execution of code block or upon (before) some catch down in call stack (parent calls are down, right?).
If it wouldn't be about disposing, then
try { ...; return true; } // only one return
finally { ... }
is enough, since you will never have to return false at the end of method (there is no need for that line). Your method is either return result of command execution (true or false) or will throw an exception otherwise.
Consider also to throw own exceptions by wrapping expected exceptions (check out InvalidOperationException constructor):
try { ... }
catch(SomeExpectedException e)
{
throw new SomeBetterExceptionWithExplanaition("...", e);
}
This is typically used to say something more meaningful (useful) to the caller than nested call exception would be telling.
Most of times you don't really care about unhandled exceptions. Sometimes you need to ensure that finally is called even if exception is unhandled. In this case you simply catch it yourself and re-throw (see this answer):
try { ... }
catch { ...; throw; } // re-throw
finally { ... }
add a comment |
The warning is because you didn't use catch and your method is basically written like this:
bool SomeMethod()
{
return true;
return false; // CS0162 Unreachable code detected
}
Since you use finally solely to dispose, the preffered solution is to utilize using pattern:
using(var command = new WhateverCommand())
{
...
}
That's enough, to ensure what Dispose will be called. It's guaranteed to be called either after successful execution of code block or upon (before) some catch down in call stack (parent calls are down, right?).
If it wouldn't be about disposing, then
try { ...; return true; } // only one return
finally { ... }
is enough, since you will never have to return false at the end of method (there is no need for that line). Your method is either return result of command execution (true or false) or will throw an exception otherwise.
Consider also to throw own exceptions by wrapping expected exceptions (check out InvalidOperationException constructor):
try { ... }
catch(SomeExpectedException e)
{
throw new SomeBetterExceptionWithExplanaition("...", e);
}
This is typically used to say something more meaningful (useful) to the caller than nested call exception would be telling.
Most of times you don't really care about unhandled exceptions. Sometimes you need to ensure that finally is called even if exception is unhandled. In this case you simply catch it yourself and re-throw (see this answer):
try { ... }
catch { ...; throw; } // re-throw
finally { ... }
add a comment |
The warning is because you didn't use catch and your method is basically written like this:
bool SomeMethod()
{
return true;
return false; // CS0162 Unreachable code detected
}
Since you use finally solely to dispose, the preffered solution is to utilize using pattern:
using(var command = new WhateverCommand())
{
...
}
That's enough, to ensure what Dispose will be called. It's guaranteed to be called either after successful execution of code block or upon (before) some catch down in call stack (parent calls are down, right?).
If it wouldn't be about disposing, then
try { ...; return true; } // only one return
finally { ... }
is enough, since you will never have to return false at the end of method (there is no need for that line). Your method is either return result of command execution (true or false) or will throw an exception otherwise.
Consider also to throw own exceptions by wrapping expected exceptions (check out InvalidOperationException constructor):
try { ... }
catch(SomeExpectedException e)
{
throw new SomeBetterExceptionWithExplanaition("...", e);
}
This is typically used to say something more meaningful (useful) to the caller than nested call exception would be telling.
Most of times you don't really care about unhandled exceptions. Sometimes you need to ensure that finally is called even if exception is unhandled. In this case you simply catch it yourself and re-throw (see this answer):
try { ... }
catch { ...; throw; } // re-throw
finally { ... }
The warning is because you didn't use catch and your method is basically written like this:
bool SomeMethod()
{
return true;
return false; // CS0162 Unreachable code detected
}
Since you use finally solely to dispose, the preffered solution is to utilize using pattern:
using(var command = new WhateverCommand())
{
...
}
That's enough, to ensure what Dispose will be called. It's guaranteed to be called either after successful execution of code block or upon (before) some catch down in call stack (parent calls are down, right?).
If it wouldn't be about disposing, then
try { ...; return true; } // only one return
finally { ... }
is enough, since you will never have to return false at the end of method (there is no need for that line). Your method is either return result of command execution (true or false) or will throw an exception otherwise.
Consider also to throw own exceptions by wrapping expected exceptions (check out InvalidOperationException constructor):
try { ... }
catch(SomeExpectedException e)
{
throw new SomeBetterExceptionWithExplanaition("...", e);
}
This is typically used to say something more meaningful (useful) to the caller than nested call exception would be telling.
Most of times you don't really care about unhandled exceptions. Sometimes you need to ensure that finally is called even if exception is unhandled. In this case you simply catch it yourself and re-throw (see this answer):
try { ... }
catch { ...; throw; } // re-throw
finally { ... }
answered 11 hours ago
SinatrSinatr
12.8k748143
12.8k748143
add a comment |
add a comment |
It seems, you are looking for something like this:
private static bool createRecord(string table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
// using: do not call Dispose() explicitly, but wrap IDisposable into using
using (var command = ...) {
try {
// Normal flow:
command.CommandText = sb.ToString();
// true if and only if exactly one record affected
return command.ExecuteNonQuery() == 1;
}
catch (DbException) {
// Exceptional flow (all database exceptions)
return false;
}
}
}
please, note, that finally doesn't swallow any exception
finally {
// this code will be executed; the exception will be efficently re-thrown
}
// and this code will never be reached
add a comment |
It seems, you are looking for something like this:
private static bool createRecord(string table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
// using: do not call Dispose() explicitly, but wrap IDisposable into using
using (var command = ...) {
try {
// Normal flow:
command.CommandText = sb.ToString();
// true if and only if exactly one record affected
return command.ExecuteNonQuery() == 1;
}
catch (DbException) {
// Exceptional flow (all database exceptions)
return false;
}
}
}
please, note, that finally doesn't swallow any exception
finally {
// this code will be executed; the exception will be efficently re-thrown
}
// and this code will never be reached
add a comment |
It seems, you are looking for something like this:
private static bool createRecord(string table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
// using: do not call Dispose() explicitly, but wrap IDisposable into using
using (var command = ...) {
try {
// Normal flow:
command.CommandText = sb.ToString();
// true if and only if exactly one record affected
return command.ExecuteNonQuery() == 1;
}
catch (DbException) {
// Exceptional flow (all database exceptions)
return false;
}
}
}
please, note, that finally doesn't swallow any exception
finally {
// this code will be executed; the exception will be efficently re-thrown
}
// and this code will never be reached
It seems, you are looking for something like this:
private static bool createRecord(string table,
IDictionary<String,String> data,
System.Data.IDbConnection conn,
OdbcTransaction trans) {
[... some other code ...]
// using: do not call Dispose() explicitly, but wrap IDisposable into using
using (var command = ...) {
try {
// Normal flow:
command.CommandText = sb.ToString();
// true if and only if exactly one record affected
return command.ExecuteNonQuery() == 1;
}
catch (DbException) {
// Exceptional flow (all database exceptions)
return false;
}
}
}
please, note, that finally doesn't swallow any exception
finally {
// this code will be executed; the exception will be efficently re-thrown
}
// and this code will never be reached
edited 12 hours ago
answered 12 hours ago
Dmitry BychenkoDmitry Bychenko
109k1094135
109k1094135
add a comment |
add a comment |
When the exception is thrown, the stack will unwind (execution will move out of the function) without returning a value, and any catch block in the stack frames above the function will catch the exception instead.
Hence, return false will never execute.
Try manually throwing an exception to understand the control flow:
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
// Try this.
throw new Exception("See where this goes.");
return returnValue == 1;
} finally {
command.Dispose();
}
add a comment |
When the exception is thrown, the stack will unwind (execution will move out of the function) without returning a value, and any catch block in the stack frames above the function will catch the exception instead.
Hence, return false will never execute.
Try manually throwing an exception to understand the control flow:
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
// Try this.
throw new Exception("See where this goes.");
return returnValue == 1;
} finally {
command.Dispose();
}
add a comment |
When the exception is thrown, the stack will unwind (execution will move out of the function) without returning a value, and any catch block in the stack frames above the function will catch the exception instead.
Hence, return false will never execute.
Try manually throwing an exception to understand the control flow:
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
// Try this.
throw new Exception("See where this goes.");
return returnValue == 1;
} finally {
command.Dispose();
}
When the exception is thrown, the stack will unwind (execution will move out of the function) without returning a value, and any catch block in the stack frames above the function will catch the exception instead.
Hence, return false will never execute.
Try manually throwing an exception to understand the control flow:
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
// Try this.
throw new Exception("See where this goes.");
return returnValue == 1;
} finally {
command.Dispose();
}
answered 12 hours ago
NisargNisarg
11.1k52241
11.1k52241
add a comment |
add a comment |
On your code:
private static bool createRecord(String table, IDictionary<String,String> data, System.Data.IDbConnection conn, OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1; // You return here in case no exception is thrown
} finally {
command.Dispose(); //You don't have a catch so the exception is passed on if thrown
}
return false; // This is never executed because there was either one of the above two exit points of the method reached.
}
the finally block would be executed, then would execute the return false; at the bottom
This is the flaw in your logic because the finally block won't catch the exception and it will never reach the last return statement.
add a comment |
On your code:
private static bool createRecord(String table, IDictionary<String,String> data, System.Data.IDbConnection conn, OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1; // You return here in case no exception is thrown
} finally {
command.Dispose(); //You don't have a catch so the exception is passed on if thrown
}
return false; // This is never executed because there was either one of the above two exit points of the method reached.
}
the finally block would be executed, then would execute the return false; at the bottom
This is the flaw in your logic because the finally block won't catch the exception and it will never reach the last return statement.
add a comment |
On your code:
private static bool createRecord(String table, IDictionary<String,String> data, System.Data.IDbConnection conn, OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1; // You return here in case no exception is thrown
} finally {
command.Dispose(); //You don't have a catch so the exception is passed on if thrown
}
return false; // This is never executed because there was either one of the above two exit points of the method reached.
}
the finally block would be executed, then would execute the return false; at the bottom
This is the flaw in your logic because the finally block won't catch the exception and it will never reach the last return statement.
On your code:
private static bool createRecord(String table, IDictionary<String,String> data, System.Data.IDbConnection conn, OdbcTransaction trans) {
[... some other code ...]
int returnValue = 0;
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
return returnValue == 1; // You return here in case no exception is thrown
} finally {
command.Dispose(); //You don't have a catch so the exception is passed on if thrown
}
return false; // This is never executed because there was either one of the above two exit points of the method reached.
}
the finally block would be executed, then would execute the return false; at the bottom
This is the flaw in your logic because the finally block won't catch the exception and it will never reach the last return statement.
answered 12 hours ago
meJustAndrewmeJustAndrew
2,92932349
2,92932349
add a comment |
add a comment |
The last statement return false is unreachable, because the try block is missing a catch part that would handle the exception, so the exception is rethrown after the finally block and the execution never reaches the last statement.
add a comment |
The last statement return false is unreachable, because the try block is missing a catch part that would handle the exception, so the exception is rethrown after the finally block and the execution never reaches the last statement.
add a comment |
The last statement return false is unreachable, because the try block is missing a catch part that would handle the exception, so the exception is rethrown after the finally block and the execution never reaches the last statement.
The last statement return false is unreachable, because the try block is missing a catch part that would handle the exception, so the exception is rethrown after the finally block and the execution never reaches the last statement.
edited 12 hours ago
answered 12 hours ago
Martin StaufcikMartin Staufcik
2,05311526
2,05311526
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55116849%2funreachable-code-but-reachable-with-exception%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
– Anton Z
12 hours ago
24
Side note: do not call
Disposeexplicitly, but putusing:using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }– Dmitry Bychenko
12 hours ago