So, I am getting an exception in Stored Procedure whose error code is 547. I have created a data diagram in sql server, where I have defined the relationships.when I run the any delete SP I get an error saying FK conflict, which is right. My problem is how do I get the number(i.e 547) in my C# code.
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
I sthere any way where I can get this 547 code in my C# code.? Like
ex.somethin (which gives me the error message's code).
Try This.
try
{
}
catch(SqlException ex)
{
lblMessage.Text = ex.Message;
}
Multiple catches can be used:
try
{
}
catch(SqlException sqlex)
{
if(sqlex.Number ==547)
{
//code
}
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
}
You can try using Elmah library (Error Logging Modules And Handlers)
Here is a step by step tutorial on how to use it: http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/logging-error-details-with-elmah-cs
For more details http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.aspx
try
{
...
...
}
catch(SqlException ex)
{
lblMessage.Text = ex.Message;
}
Related
This question already has answers here:
Catching exceptions with "catch, when"
(3 answers)
C# 7 Pattern Matching
(2 answers)
Closed 2 years ago.
I need to catch a generic exception and then categorize is based on a specific type to reduce the no of lines of code as all the exception does the same thing .
Something like below
catch (Exception ex)
{
Type ExceptionType = ex.GetType();
switch (ExceptionType.ToString())
{
case "IOException":
case "NullReferenceException":
system.WriteLine((ExceptionType)ex.Message);
break;
}
This shows error there is no type Exception type. Is there a possiblity to try this approach and accomplish this or need to take a typical if else approach.
Please help
Ideally you should handling each Exception individually like so:
try
{
}
catch (IOException ex)
{
// Log specific IO Exception
}
catch (NullReferenceException ex)
{
// Log Specific Null Reference Exception
}
catch (Exception ex)
{
// Catch everything else
}
You could do:
string exceptionErrorMessage;
try
{
}
catch (IOException ex)
{
// Log specific IO Exception
exceptionErrorMessage = ex.Message;
}
catch (NullReferenceException ex)
{
// Log Specific NullReferenceException
exceptionErrorMessage = ex.Message;
}
catch (Exception ex)
{
// Catch everything else
exceptionErrorMessage = ex.Message;
}
if (!string.IsNullOrEmpty(exceptionErrorMessage))
{
// use your logger to log exception.
Console.WriteLine(exceptionErrorMessage);
}
Here's the correct to OPs code using the same method he wanted:
try
{
}
catch (Exception e)
{
var exType = e.GetType().Name;
switch (exType)
{
case "IOException":
case "NullReferenceException":
Console.WriteLine(e.Message);
break;
}
}
It sounds like you may be looking for ex.GetType().Name!
In terms of a full solution, that should work with your existing code.
I'm not familiar with exception handling (not much of a developer).
How do I catch an exception when a database doesn't exist or is offline? Do I need to throw a new Exception? The following gets me the warning "Exception was unhandled by user code"
catch (Exception err)
{
if (err is OracleException)
{
//database does not exist?
ErrorMessage = err.Message;
throw new Exception(ErrorMessage);
}
else
{
ErrorMessage = err.Message;
con.Close();
throw new Exception(ErrorMessage);
}
The 'Catch' expression is used to handle the Exception. If you are throwing another Exception, it needs to be catched somewhere.
And C# allows you to catch more than one exceptions, so you can do this:
try
{
//TRY TO OPEN THE CONNECTION
}
catch (OracleException oraExcep)
{
//DO SOMETHING IF A OracleException
//ERROR IS HANDLED HERE
}
catch (Exception ex)
{
//DO SOMETHING ELSE
}
I'm building a wpf application with a database in entity framework code first.
I allow the user to delete items in database, but when item is linked to other data, an exception will be thrown.
This is what I had originally
try
{
//delete item
}
catch (Exception ex)
{
MessageBox.Show(ex.Message)
}
This is working, but the message displayed isn't so much user firendly. So I tried to create a custom exception
public class CustomException : Exception
{
public CustomException (string Message)
{
Message = "Item can't be deleted";
}
}
And I've modified my catch
catch (CustomException ex)
{
MessageBox.Show(ex.Message)
}
But this is not showing the messagebox with my message, but it's stopping my application for a DbUpdateException.
Is there a way to customize the message for this type of exception?
Modifying the catch won't change how the framework throws an exception. You should just catch the DbUpdateException and show a message that is appropriate:
catch (DbUpdateException ex)
{
MessageBox.Show("item can't be deleted");
}
In c#, can I catch all errors about (non) connectivity to an Oracle database?
I don't want to catch error about badly written query but only errors like No listener, connection lost...
If queries are badly written (or table are missing) then this is my fault.
But if Oracle or the network is down then this should be held by another department.
Write your code in which you build the connection in a try catch part:
try
{
BuildConnection(connectionString);
}
catch (OracleException ex)
{
//Connectivity Error
}
Errors between ORA-12150 to ORA-12236 are related to connection errors. A few examples:
ORA-12154: TNS:could not resolve the connect identifier specified
ORA-12152: TNS:unable to send break message
ORA-12157: TNS:internal network communication error
Please refer to https://docs.oracle.com/cd/E11882_01/server.112/e17766/net12150.htm
Simple answer for this Type of problem is Use Try Catch Block like
try
{
// your code
}
catch (OracleException ex)
{
}
MSDN HELP
Sure - you can catch specific exception types, or if they're all the same exception type, you can catch it, check to see if it's a specific type, and re-throw ones you don't want to handle. Not having your syntax, here's an example...
try
{
// your Oracle code
}
catch (OracleException ex)
{
if (ex.Message == "Something you don't want caught")
{
throw;
}
else
{
// handle
}
}
errors like No listener, connection lost are still caught in System.Data.SqlClient.SqlException, however, you may inspect ErrorCode and Errors to handle different situations accordingly, say, not listener or connection lost etc.
MSDN does not seem to document all possible errors, however, you may write a few unit tests or integration tests to learn what appear in ErrorCode and Errors, then write error handlers in production codes accordingly.
OracleException contains only ErrorCode not Errors. So you may be using switch(e.ErrorCode) to handle different situations.
I observed that each time a network exception occurs, then a SocketException can be found in inner exceptions.
I also observed that when a network exception occurs, the first inner exception is of type «OracleInternal.Network.NetworkException» but unfortunately, this class is internal...
Based on this observations, I would code something like this:
public void RunQuery()
{
try
{
var con = new OracleConnection("some connection string");
con.Open();
var cmd = con.CreateCommand();
// ...
cmd.ExecuteNonQuery();
}
catch (Exception ex) when (IsNetworkException(ex))
{
// Here, a network exception occurred
}
catch (Exception ex)
{
// Here, an other exception occurred
}
}
private static bool IsNetworkException(Exception ex)
{
var exTmp = ex;
while (exTmp != null)
{
if (exTmp is SocketException)
return true;
exTmp = exTmp.InnerException;
}
return false;
}
I have a method that can throw two different exceptions, CommuncationException and SystemException. In both cases I do the same three-line code block.
try {
...
}
catch (CommunicationException ce) {
...
}
catch {SystemExcetion se) {
...
}
Is there any possibility to do it like that?
try {
...
}
catch (CommunicationException ce, SystemException se) {
...
}
Then I would not have to write this much code. I know I could extract the exception handling to a private method, but since the code is only 3 lines long, the method definition would take more code than the body itself.
If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:
catch (Exception ex) when (ex is CommunicationException || ex is SystemException) {
//handle it
}
Some people think this code is the same as
catch (Exception ex) {
if (ex is CommunicationException || ex is SystemException) {
//handle it
}
throw;
}
But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.
See a discussion about this on CodePlex. And an example showing the difference.
In fact, you could catch only SystemException and it would handle CommunicationException too, because CommunicationException is derived from SystemException
catch (SystemException se) {
... //this handles both exceptions
}
Unfortunately, there is no way. The syntax you used is invalid and a fall through like in a switch-statement isn't possible either. I think you need to go with the private method.
A little hacky work-around would be something like this:
var exceptionHandler = new Action<Exception>(e => { /* your three lines */ });
try
{
// code that throws
}
catch(CommuncationException ex)
{
exceptionHandler(ex);
}
catch(SystemException ex)
{
exceptionHandler(ex);
}
You need to decide for yourself if this makes any sense.
No, you can't do it that way. The only way i know of is to catch a generic Exception and then check what type it is:
try
{
...
}
catch(Exception ex)
{
if(ex is CommunicationException || ex is SystemException)
{
...
}
else
{
... // throw; if you don't want to handle it
}
}
What about
try {
...
}
catch (CommunicationException ce) {
HandleMyError(ce);
}
catch {SystemExcetion se) {
HandleMyError(se);
}
private void HandleMyError(Exception ex)
{
// handle your error
}
Possible Duplicate of
Catch multiple exceptions at once?
I quote the answer here:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}
Dragging this one up from the depths of history as it happened to pop up in some search results.
With the advent of C# 7.0 (which arrived in 2017 with VS2017, .net framework 4.7 and dotnet core 2.0) you can now do things like this:
try {
...
}
catch (Exception e) when (e is CommunicationException || e is SystemException) {
...
}
Since you're doing the same for both type of exceptions, you could just go:
try
{
//do stuff
}
catch(Exception ex)
{
//normal exception handling here
}
Only catch explicit Exception types if you need to do something unique for it.