I'm trying to catch specific SqlException 515 (Cannot insert the value NULL into column), and I cannot precheck the value before the actual INSERT. I can only capture the error and determine what error it was.
In the following execution, the alert() can display of these msgs: that there's an empty value somewhere (from SqlException 515) or the generic error saying that something's wrong.
In this case, I know I can create and throw a custom exception error, but I would like to use only what I have here available since the SqlException will capture the exact error.
Also, those two methods are in two different classes and I only want to include System.Data.SqlClient where the Insert() method is.
Finally, I can use the regular System.Exception with substring method and search for a particular string. But there should be a better way.
So here's my pseudocode:
public void InsertNewCar()
{
try
{
Car myCar = new Car();
myCar.Insert();
}
catch (Exception ex)
{
alert(msg); //Alerts the user: "Something missing" or "generic error"
}
}
public void Insert()
{
try
{
SqlHelper.ExecuteNonQuery(ConnString, CommandType.Text, sqlInsert);
}
catch (SqlException ex)
{
if (ex.Number == 515)
{
//throw exception specifying that something's missing in the INSERT
}
else
{
throw ex; //throw ex that will be interpreted as a generic error.
}
}
}
My question is: once I capture SqlException 515, what can I do with it? Once I throw it, I cannot check for error number within InsertNewCar().
I can have Insert() return a value, but then the Exception will not be thrown. And I don't want to use ref keyword.
Thanks.
You could rethrow it with a specific, other exception:
throw new SomethingMissingException("Some guiding text", ex /*the original exception*/);
In that way, you can handle it somewhere else in a more generic way. Also, don't forget to add the original exception to the exception you throw. It may come in handy some time.
Related
I'm trying to create a validation strategy for user input. But I keep getting a CS0155 error.
I've tried throwing an exception but it doesn't get rid of the error.
catch (OverflowAction)
{
Debug.WriteLine(
"{0}.Validate: Int32 overflow (\"{1}\").",
GetType(), str);
string errmsg = Properties.Resources.OverflowError;
return new ValidationResult(false, errmsg);
//throw new NotImplementedException();
}
I expect the validator to catch the exception and return an error message.
This error indicates that your OverflowAction class does not inherit from Exception (or derived one).
See CS0155 error documentation.
Only data types that derive from System.Exception can be passed into a catch block.
OverflowAction should looke like
class OverflowAction : Exception
{
// ...
}
You might be confusing OverflowAction with OverflowException ...
This question already has answers here:
Why catch and rethrow an exception in C#?
(17 answers)
Closed 6 years ago.
I have some code which catches the exception, rolls back the transaction and then rethrow the exception.
catch ( Exception exSys ) {
bqBusinessQuery.RollBackTransaction();
throw exSys ;
}
If I use this code, VS Code analysis throws warning saying
Use 'throw' without an argument instead, in order to preserve the stack location where the exception was initially raised.
If I use the code
catch ( Exception exSys ) {
bqBusinessQuery.RollBackTransaction();
throw;
}
then I get a warning saying
The variable 'exSys' is declared but never used
How should I solve this problem?
Edit
I tried this method, but it doesn't work. system.exception class requires an extra message, along with inner exception. If I do that, it will throw a new message overriding the message from the original exception. I don't want to get the new exception, I want to throw the same exception with same message.
catch (System.Exception ex)
{
throw new System.Exception(ex);
}
Edit
catch (System.Exception ex)
{
throw new System.Exception("Test",ex);
}
Tried this method. And then manually caused an exception using throw new Exception("From inside");. Now, ex.Message returns "Test" instead of "From inside". I want to keep that "From inside" message as is. This suggested change will cause problem with error display code everywhere. :/
You do not have to bind a variable to the exception:
try
{
...
}
catch (Exception)
{
bqBusinessQuery.RollBackTransaction();
throw;
}
Actually, in your case, as you catch any exception, you do not have to even name the exception type:
try
{
...
}
catch
{
bqBusinessQuery.RollBackTransaction();
throw;
}
Or (as suggested #Zohar Peled) throw a new exception, using the caught exception as an inner exception. This way you both preserve the stack and give the exception more context.
try
{
...
}
catch (Exception e)
{
throw new Exception("Transaction failed", e);
}
If you actually want to use the exception for some processing (e.g. log it), but want to rethrow it intact, declare the variable, but use a plain throw:
try
{
...
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
catch (Exception)
{
bqBusinessQuery.RollBackTransaction();
throw;
}
If you don't plan on using the exception (e.g. passing the message somewhere) then you don't need to pull it out into a variable. You can simply catch, do custom thing and throw.
i'm calling a function that throws a custom exception:
GetLockOwnerInfo(...)
This function in turn is calling a function that throws an exception:
GetLockOwnerInfo(...)
ExecuteReader(...)
This function in turn is calling a function that throws an exception:
GetLockOwnerInfo(...)
ExecuteReader(...)
ExecuteReader(...)
And so on:
GetLockOwnerInfo(...)
ExecuteReader(...)
ExecuteReader(...)
ExecuteReaderClient(...)
Fill(...)
One of these functions throws an SqlException, although that code has no idea what an SqlException is.
Higher levels wrap that SqlException into another BusinessRuleException in order to include some special properties and additional details, while including the "original" exception as InnerException:
catch (DbException ex)
{
BusinessRuleExcpetion e = new BusinessRuleException(ex)
...
throw e;
}
Higher levels wrap that BusinessRuleException into another LockerException in order to include some special properties and additional details, while including the "original" exception as InnerException:
catch (BusinessRuleException ex)
{
LockerException e = new LockerException(ex)
...
throw e;
}
The problem now is that i want to catch the origianl SqlException, to check for a particular error code.
But there's no way to "catch the inner exception":
try
{
DoSomething();
}
catch (SqlException e)
{
if (e.Number = 247)
{
return "Someone";
}
else
throw;
}
i thought about catching SqlException right when it's thrown, and copy various values to the re-thrown exception - but that code is not dependant on Sql. It is experiencing an SqlException, but it has no dependency on SqlException.
i thought about catching all exceptions:
try
{
DoSomething(...);
}
catch (Exception e)
{
SqlException ex = HuntAroundForAnSqlException(e);
if (ex != null)
{
if (e.Number = 247)
{
return "Someone";
}
else
throw;
}
else
throw;
}
But that's horrible code.
Given that .NET does not let you alter the Message of an Exception to include additional information, what is the intended mechanism to catch original exceptions?
You need c# 6 / visual studio 2015 in order to do this using a predicate:
catch (ArgumentException e) when (e.ParamName == “…”)
{
}
Official C# Try/Catch Documentation
I hate to have to tell you this, but you cannot catch an inner exception.
What you can do is inspect one.
I suggest you catch your high-level exception (I believe it was LockerException) and inspect the InnerException property of that exception. Check the type, and if it's not a SqlException, check the InnerException of that exception. Walk each one until you find a SqlException type, then get the data you need.
That said, I agree with dasblinkenlight that you should consider -- if possible -- a heavy refactor of your exception framework.
Checking the error code of a wrapped exception is not a good practice, because it hurts encapsulation rather severely. Imagine at some point rewriting the logic to read from a non-SQL source, say, a web service. It would throw something other than SQLException under the same condition, and your outer code would have no way to detect it.
You should add code to the block catching SQLException to check for e.Number = 247 right then and there, and throw BusinessRuleException with some property that differentiates it from BusinessRuleException thrown in response to non-SQLException and SQLException with e.Number != 247 in some meaningful way. For example, if the magic number 247 means you've encountered a duplicate (a pure speculation on my part at this point), you could do something like this:
catch (SQLException e) {
var toThrow = new BusinessRuleException(e);
if (e.Number == 247) {
toThrow.DuplicateDetected = true;
}
throw toThrow;
}
When you catch BusinessRuleException later, you can check its DuplicateDetected property, and act accordingly.
EDIT 1 (in response to the comment that the DB-reading code cannot check for SQLException)
You can also change your BusinessRuleException to check for SQLException in its constructor, like this:
public BusinessRuleException(Exception inner)
: base(inner) {
SetDuplicateDetectedFlag(inner);
}
public BusinessRuleException(string message, Exception inner)
: base(message, inner) {
SetDuplicateDetectedFlag(inner);
}
private void SetDuplicateDetectedFlag(Exception inner) {
var innerSql = inner as SqlException;
DuplicateDetected = innerSql != null && innerSql.Number == 247;
}
This is less desirable, because it breaks encapsulation, but at least it does it in a single place. If you need to examine other types of exceptions (e.g. because you've added a web service source), you could add it to the SetDuplicateDetectedFlag method, and everything would work again.
Having an outer application layer care about the details of a wrapped exception is a code smell; the deeper the wrapping, the bigger the smell. The class which you now have wrapping the SqlException into a dbException is presumably designed to expose an SqlClient as a generic database interface. As such, that class should include a means of distinguishing different exceptional conditions. It may, for example, define a dbTimeoutWaitingForLockException and decide to throw it when it catches an SqlException and determines based upon its error code that there was a lock timeout. In vb.net, it might be cleaner to have a dbException type which exposes an ErrorCause enumeration, so one could then say Catch Ex as dbException When ex.Cause = dbErrorCauses.LockTimeout, but unfortunately exception filters are not usable in C#.
If one has a situation where the inner-class wrapper won't know enough about what it's doing to know how it should map exceptions, it may be helpful to have the inner-class method accept an exception-wrapping delegate which would take an exception the inner class has caught or would "like" to throw, and wrap it in a way appropriate to the outer class. Such an approach would likely be overkill in cases where the inner class is called directly from the outer class, but can be useful if there are intermediate classes involved.
Good question and good answers!
I just want to supplement the answers already given with some further thoughts:
On one hand I agree with dasblinkenlight and the other users. If you catch one exception to rethrow an exception of a different type with the original exception set as the inner exception then you should do this for no other reason than to maintain the method's contract. (Accessing the SQL server is an implementation detail that the caller is not/must not/cannot be aware of, so it cannot anticipate that a SqlException (or DbException for that matter) will be thrown.)
Applying this technique however has some implications that one should be aware of:
You are concealing the root cause of the error. In your example you are reporting to the caller that a business rule was invalid(?), violated(?) etc., when in fact there was a problem accessing the DB (which would be immediately clear if the DbException were allowed to bubble up the call stack further).
You are concealing the location where the error originally occurred. The StackTrace property of the caught exception will point to a catch-block far away from the location the error originally occurred. This can make debugging notoriously difficult unless you take
great care to log the stack traces of all the inner exceptions as well. (This is especially true once the software has been deployed into production and you have no means to attach a
debugger...)
Given that .NET does not let you alter the Message of an Exception to include additional information, what is the intended mechanism to catch original exceptions?
It is true that .NET does not allow you to alter the Message of an Exception. It provides another mechanism however to supply additional information to an Exception via the Exception.Data dictionary. So if all you want to do is add additional data to an exception, then there is no reason to wrap the original exception and throw a new one. Instead just do:
public void DoStuff(String filename)
{
try {
// Some file I/O here...
}
catch (IOException ex) {
// Add filename to the IOException
ex.Data.Add("Filename", filename);
// Send the exception along its way
throw;
}
}
As other peeps say, you cannot catch an the InnerException. A function such as this could help you get the InnerException out of the tree though:
public static bool TryFindInnerException<T>(Exception top, out T foundException) where T : Exception
{
if (top == null)
{
foundException = null;
return false;
}
Console.WriteLine(top.GetType());
if (typeof(T) == top.GetType())
{
foundException = (T)top;
return true;
}
return TryFindInnerException<T>(top.InnerException, out foundException);
}
I agree with the other comments that this is a code smell 🦨 and should be avoided. But if a refactor is not possible you could try something like this...
Create an extension method...
public static bool HasInnerException(this Exception ex, Func<Exception, bool> match)
{
if (ex.InnerException == null)
{
return false;
}
return match(ex.InnerException) || HasInnerException(ex.InnerException, match);
}
And use it like...
catch (Exception ex) when (ex.HasInnerException(e => e is MyExceptionThatIsHidden))
{
...
But really you should be solving for 👇
var exception = new Exception("wrapped exception 3",
new Exception("wrapped exception 2",
new Exception("wrapped exception 1",
new MyExceptionThatIsHidden("original exception")))); // <--- ???
following is a code snippet:
class xxx
{
public xxx(){}
try
{
throw new Exception(InvalidoperationException);
}
catch(Exception x)
{
}
catch(InvalidoperationException x)
{
}
}
can anyone tell which exception will raise here and what is the reason behind it.
Wow, lots of problems here. Where to start?
That code won't compile. The try-catch block that you've defined is outside of any method, which is not allowed. You need to move it inside of a method.
Never throw a method that you intend to catch yourself later in the method. That's commonly known as using exceptions for "flow control", which is roundly discouraged. There is a performance cost associated with doing so, and it also makes it very confusing to monitor the exceptions that are being thrown when using a debugger when you have code that's throwing and catching it's own exceptions. Use boolean variables (known as flags) for flow control, if necessary.
Always catch the most derived exception class first. That means you should catch InvalidOperationException first, before trying to catch Exception. You need to reverse the order of your catch blocks in the code that you have.
You should practically never catch System.Exception. The only exceptions that you should catch are those that you explicitly understand and are going to be able to handle. There's virtually no way that you're going to know what went wrong or how to handle it when the only information you have is that a generic exception was thrown.
Along those same lines, you also should never throw this exception from your own code. Choose a more descriptive exception class that inherits from the base System.Exception class, or create your own by inheriting from the same.
I see that other answers are showing you sample code of what your code should look like, were it to be rewritten. I'm not going to do that because if I rewrote your code to be correct, I'd end up with this:
class Xxx
{
public Xxx()
{
}
}
Not particularly helpful.
If the code is like this
class xxx
{
public xxx(){
try
{
throw new Exception(InvalidoperationException);
}
catch(InvalidoperationException x)
{
}
catch(Exception x)
{
}
}
}
It should compile and raise your exception and catch. Otherwise your code will not compile at all.
No exception will be thrown as this code will not even compile.
Regardless - several points:
When using exception handling, put the more specific exception before the less specific ones (so the catch of InvalidOperationException should be before the one for Exception).
Catching Exception is normally no very useful.
If you catch an exception, do something with it.
You probably meant:
throw new InvalidOperationException();
However, the way you structured your exceptions, the catch(Exception x) block would have run.
You should write:
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Do smth with exception;
}
catch(Exception exception)
{
throw; // Rethrows your exception;
}
}
}
InvalidOperationException inherits from Exception.
catch tries to processes the most specific branch, so catch (InvalidOperationException x) will be executed here.
Nope. It wouldn't compile. So, it there's no question about as to which exception will be generated.
Your code should be something like this :
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Something about InvalidOperationException;
}
catch(Exception exception)
{
// Something about the Exception
}
}
}
Point to be noted :
Write more specific class of Exception first, hence we write InvalidOperationException prior to Exception class.
Ignoring the compile issue.... the first matching exception block (catch(Exception x)) will get the exception. You then ignore the exception and don't re-throw, so exception will be seen by the outside world. That doesn't make it good practice, though... in particular, catching an arbitrary Exception and ignoring it is risky - it could have been anything... it isn't necessarily the exception you thought it was.
Well, the code won't compile, but I'll just ignore that...
If I'll just look at the line:
throw new Exception(InvalidoperationException);
1st of all, according to MSDN there is no such constructor. So I will assume you meant the constructor: Exception(String msg, Exception innerException). Meaning:
throw new Exception("blabla", InvalidoperationException);
The exception that is being thrown is of type Exception and not InvalidOperationException. So ONLY catch(Exception x) can catch it.
If you would've thrown InvalidoperationException than the way you wrote the order of the catches, the Exception class would get caught first.
The order of the catches does matter.
The best advice I can give you is simply try it yourself and see what happens.
I want to make a method, that throws a specific exception, by a parameter I give to the method. I have 3 userdefined exceptions, so instead of having to throw them every time I want to use them I want to make a method that handels it, so the parameter I give with my method is the exception I want to throw, but how do I do that?
I want to do something like this, but I am not really sure how to do it.
private void ExceptionMethod(custom exception)
{
try
{
//code that might fail
}
catch(exception ex)
{
throw new exception given by parameter(parameters from the exception);
}
}
FWIW I don't think this is a particulary good idea. Really, just throw your exception where it occurs, future maintainers of the code will thank you. (or at least not curse you)
If you have to do this thing, then its probably a better idea to pass an enumeration that you can switch on rather than the exception itself, then simply write a case statement to throw the exception you want.
Apart from the fact that this sounds like a bad idea, you can try the following:
private void TryElseThrow<TCustomException>(Action codeThatMightFail)
where TCustomException : Exception
{
try
{
codeThatMightFail();
}
catch (Exception e)
{
// Since there isn't a generic type constraint for a constructor
// that expects a specific parameter, we'll have to risk it :-)
throw
(TCustomException)Activator
.CreateInstance(typeof(TCustomException), e);
}
}
Use like so:
TryElseThrow<MyCustomException>(
() =>
{
throw new InvalidOperationException();
}
);
You were actually quite close:
private void ExceptionMethod(Exception customException)
{
try
{
//code that might fail
}
catch(Exception ex)
{
throw customException;
}
}
Will work, though I wouldn't recommend it for two reasons:
Catching Exception is a bad idea - you should just catch the exceptions that your code raises.
It's not a very good design (as others have pointed out).
So i dont see any problem in that.. as you say you already have your Custom Exception Written then you can do it like this.
in your parameter:
private void ExceptionMethod(CustomException myexception)
in catch:
throw myexception;
though its not a good Coding Design
Wouldn't it just be:
private void ExceptionMethod(MyCustomException exception)
{
try
{
//code that might fail
}
catch
{
throw exception;
}
}