I have an exception occurred when the Database connection failed in a Class. The problem is how do I notify my Main Window that this exception is caught and show a message box to notify my user?
Thanks
Use the Try ... Catch clause like this:
try
{
// The code that could generate an exception
}
catch(Exception ex)
{
MessageBox.Show("Error: " ex.Message);
}
Or if you're using SQL-Server connection, use it like this:
try
{
// The code that could generate an exception
}
catch(SqlException ex)
{
MessageBox.Show("SQL Error: " ex.Message);
}
Thanks. I may have not make my question clearly. I mean this exception
is occurred in one class, but the message box should be show in an
other windows class. So how do I communicate and show this error?
From your clarification in one of the comments:
So if you have class TestClass.cs with method Test in it.
public void Test()
{
//if you want to throw an exception defined by your business logic
if(someCondition == false)
throw CustomException();
//if you have exception in the code
int a = 5;
int b =0;
//here you will be thrown an exception can't divide by 0.
int c = a/b;
}
Your winform Button Click or whatever
public void Button_Click1(object sender, EventArgs e)
{
try
{
TestClass cl = new TestClass();
cl.Test();
}
catch(CustomException custEx)
{
//this for your Bussines logic exception
//write your message
}
catch(DivideByZeroException div)
{
//this for divide by zero exception
//write message
}
//you can catch all other exception like this but I don't advice you to do that
catch(Exception ex)
{
//for this to working properly, this catch should be under all of others(last priority)
}
}
Related
I have tried this code to raise a manual exception
protected void test ()
try
{
throw new Exception("HI"); //line22
}
catch (Exception ex) { lblerror.Text = ex.ToString(); }
but received exception below
System.ArgumentException: HI at
Project_Test_M_Test.btnsubmit_Click(Object sender, EventArgs e) in
D:\Project\Test\M_Test.aspx.cs:line 22
I want to see error message that I have send not this.
Please use ex.Message instead of ex.ToString().
btw, its not a good idea to throw the base class Exception. please use a more specific one.
This is what you need to do, use Message property to access the error message.
protected void test ()
{
try
{
throw new Exception("HI"); // Exception message passed from constructor
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
}
The following is my code in C#:
catch(Exception ex)
{
ex.Data.Add("VarName", "object");
throw;
}
Question: doing above, am I going to lose the entry I am adding to Data dictionary? -->as in my opinion, I am rethrowing the exception caught in the catch statement, and it does not have the added Dictionary record from the next line yet.
Should above code instead be:
catch(Exception ex)
{
ex.Data.Add("VarName", "object");
throw ex;
}
but in this case, I don't want to reset the stack trace.
Searched this all over the web and on SO, but no luck.
TIA!
Your initial code should work just fine. You should not lose the dictionary entry.
[EDIT]: Elaboration.
Let's take the following example code:
using System;
class Program
{
static void Main()
{
Change();
Replace();
Inner();
}
static void Change()
{
try {
try {
throw new Exception("This is a message");
} catch (Exception e) {
e.Data.Add("foo", "bar");
throw;
}
} catch (Exception e) {
System.Diagnostics.Trace.WriteLine(e.Message);
System.Diagnostics.Trace.WriteLine(e.Data["foo"]);
}
}
static void Replace()
{
try {
try {
throw new Exception("This is a message");
} catch (Exception e) {
e = new Exception("Different message", e);
e.Data.Add("foo", "bar");
throw;
}
} catch (Exception e) {
System.Diagnostics.Trace.WriteLine(e.Message);
System.Diagnostics.Trace.WriteLine(e.Data["foo"]);
}
}
static void Inner()
{
try {
try {
throw new Exception("This is a message");
} catch (Exception e) {
e.Data.Add("foo1", "bar1");
e = new Exception("Different message", e);
e.Data.Add("foo2", "bar2");
throw e;
}
} catch (Exception e) {
System.Diagnostics.Trace.WriteLine(e.Message);
System.Diagnostics.Trace.WriteLine(e.Data["foo2"]);
System.Diagnostics.Trace.WriteLine(e.InnerException.Message);
System.Diagnostics.Trace.WriteLine(e.InnerException.Data["foo1"]);
}
}
}
When throwing an Exception, what is really thrown is a reference to an Exception object. That reference is what is caught and rethrown. Modifying the underlying object is fine. This is what your initial code does, and what the Change method in my example does.
In the Replace method we modify not the object, but the reference itself. We make it point to a brand new Exception object with a different message and to top it off we also add some data. All this stuff is lost, though, because throw without arguments rethrows the original reference.
Should the need arise to use the second case, you can keep track of your stack trace by including the original exception as InnerException, like I did in the Inner method.
I have the following method in the class ProductServices:
public bool IsDownloadAllowed(int Id, string productId)
{
if (CustomStringFunctions.IsGuid(productId))
{
//Do Something
}
else
{
throw new FormatException("The Guid must be a valid Guid!");
}
}
If I use the method in the following set of instructions:
var _productServices = new ProductServices();
try
{
var flag = _productServices.IsDownloadAllowed(Id, productId);
//do something
}
catch (Exception e)
{
//handle exception
}
The exception is not caught by the catch statement. I also tried to replace Exception with FormatException with no luck. What am I doing wrong?
You must have mute exception in this code
if (CustomStringFunctions.IsGuid(productId))
{
//Do Something
}
You must be sure that you throw exception when occured (In the Do Something)
Sample of mute exception
Try
{
}
Catch(Exception ex)
{
//throw don't exist
}
Your code looks correct. A possible explanation for your problem is that CustomStringFunctions.IsGuid is incorrectly returning true, so the \\do something branch is executing instead of the exception-throwing branch.
Using c# code within a web application, I have a try catch statement in my code and within the catch I want to do several things such as email an administrator.
I am wondering what would happen if the email code or other code within the catch fails? Is there a way to handle a general exception in the application?
Description
There are 2 things you can do to catch unhandled exceptions. Application.ThreadException and AppDomain.CurrentDomain.UnhandledException
Application.ThreadException Occurs when an untrapped thread exception is thrown.
AppDomain.CurrentDomain.UnhandledException Occurs when an exception is not caught.
Handle a exception inside the catch block.
Sample
Application.ThreadException and AppDomain.CurrentDomain.UnhandledException
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Handle a exception inside the catch block.
try
{
// do something
}
catch (Exception ex)
{
try
{
// send E-Mail
}
catch
{
// handle
}
}
More Information
Application.ThreadException Event
AppDomain.UnhandledException Event
If an exception is thrown within the catch clause, it simply raises another exception. One way to solve it is to simply have a nested try, eg.
try {
<stuff>
} catch(Exception e) {
try {
<email admin>
catch(EmailException e2) {
<stuff>
}
<stuff>
}
One approach is to handle the exception within the catch statement:
try
{
// Do stuff
}
catch (SpecificException ex)
{
try
{
// Try e-mailing
}
catch (AnotherException ex1)
{
// Write local log file
}
}
this will allow the program to continue.
However, if the program can't you can handle all unhandled exceptions at the application level and do something there.
Sure, you will have to surround the routine where you have your try catch with another try catch, or write your code in the catch statement surrounded with a try catch statement.
you can try aplication exception, if it's fatal error. , though its become obsolete Checkthis now in .net framework.
Application exceptions
public sealed class Product
{
private String name;
public String Name
{
get { return name; }
set
{
if (value != null) name = value;
else throw new UndefinedNameException();
}
}
public sealed class UndefinedNameException : ApplicationException
{
public UndefinedNameException() : base("Name cannot be null") {}
}
} // end of class Product
If the exception is thrown in catch block it will be propagated the normal way exceptions are.
You will need the following code:
try
{
//code
}
catch (SomeKindOfError e1)
{
try
{
// send email
}
catch (EmailError e2)
{
}
}
Your exception would be caught by any outer block where it is eligible, e.g. if you have:
try
{
// ...
try {
//code
}
catch (SomeKindOfErrorThatIsNotEmailError e1)
{
// send email
}
// ...
}
catch
{
// your email exception will get caught here
}
I am wondering what would happen if the email code or other code within the catch fails?
The exception thrown within catch will be handled by CLR Default Handler if not enclosed within another try-catch pair.
However finally will definitely execute. so you can use it to clearing or closing the resources.
Is there a way to handle a general exception in the application?
within main method, write following code part:
try
{
// write normal code
}
catch(Exception e)
{
// if here exception occurs ... God Help.
}
this is for a windows application
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
}
static void Application_ThreadException(Object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Application.ThreadException");
}
static void AppDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(((Exception)e.ExceptionObject).Message, "AppDomain.UnhandledException");
}
There is no incompatibily with the fact to use a try catch sequence in a catch snippet
Logically, you won't catch the same exception so you can know what part failed
Lot of guys gave u the code to use, accept one of these answers
Here's an interesting question. I have a system that attempts to run some initialization code. If it fails, we call the deinitializer to clean everything up.
Because we call the deinitializer in exception handling, we run the risk that both initialize and deinitialize will fail, and hypothetically, it now seems that we have to throw two exceptions.
It seems pretty unlikely that we will, though. So what happens and what should the code do here?
try { /* init code here */ }
catch (Exception ex)
{
try
{
_DeinitializeEngine();
}
catch (Exception ex2)
{
throw new OCRException("Engine failed to initialize; ALSO failed to deinitialize engine!", ex2);
}
finally
{
throw new OCRException("Engine failed to initialize; failed to initialize license!", ex);
}
}
You shouldn't throw in the Finally block. Instead, use the InnerException to add information in the throw.
Update
What you have to do is to catch and rethrow with the "history" of exception, this is done with InnerException. You can edit it when bulding a new exception. This is a code snippet I just wrote to illustrate the idea that I explain in all the comments below.
static void Main(string[] args)
{
try
{
principalMethod();
}
catch (Exception e)
{
Console.WriteLine("Test : " + e.Message);
}
Console.Read();
}
public static void principalMethod()
{
try
{
throw new Exception("Primary");
}
catch (Exception ex1)
{
try
{
methodThatCanCrash();
}
catch
{
throw new Exception("Cannot deinitialize", ex1);
}
}
}
private static void methodThatCanCrash()
{
throw new NotImplementedException();
}
No need to use double throw with finalize. If you put a break point at the Console.WriteLine(...). You will notice that you have all the exception trace.
If your clean up code is failing and you cannot leave the application in a clean and known state I would let the exception go unhandled (or catch it with the UnhandledException event to log it) then close the application.
Because if you can't handle the first exception, what point is there in catching the second exception?
If I understand your problem correctly, here's what I would have done:
try { /* init code here */ }
catch (Exception ex)
{
// Passing original exception as inner exception
Exception ocrex = new OCRException("Engine failed to initialize", ex);
try
{
_DeinitializeEngine();
}
catch (Exception ex2)
{
// Passing initialization failure as inner exception
ocrex = new OCRException("Failed to deinitialize engine!", ocrex);
}
throw ocrex;
}
You have two possible exception conditions: one in which the first method failed, and one in which both methods failed.
You're already defining your own exception class. So create another (or extend the first) with a RelatedException or PriorException property. When you throw the exception in the second case, save a reference to the first exception in this property.
It's up to the exception handler that catches this exception to figure out what to do with the second exception.