FileNotFoundExceptions for System.Data.SQLite not catched - c#

I use System.Data.SQLite in my project. When there is no System.Data.SQLite dll in output folder I can't catch FileNotFoundException (other exception catched fine). Here is the code exapmle:
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
SQLiteConnection conn = new SQLiteConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox doesn't showed. If I extract this code in separate function and wrap this function call in try catch than catching exception work fine and MessageBox showed:
private void DeclareConnection()
{
SQLiteConnection conn = new SQLiteConnection();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
DeclareConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What is the problem?

You will have to handle the AppDomain.AssemblyResolve event,
Subscribe to the AssemblyResolve event
AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve;
here is some example code that handles the loading of x86 / x64 SQLite assemblies in c#
public static Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name.Contains("System.Data.SQLite"))
{
if (_assembliesResolved)
return null;
Assembly returnValue;
string executingAssemblyPath = Assembly.GetExecutingAssembly().Location;
executingAssemblyPath = Path.GetDirectoryName(executingAssemblyPath);
if (Environment.Is64BitProcess)
executingAssemblyPath = Path.Combine(executingAssemblyPath, #"lib-sqlite\x64\", "System.Data.SQLite.dll");
else //32 bit process
executingAssemblyPath = Path.Combine(executingAssemblyPath, #"lib-sqlite\x86\", "System.Data.SQLite.dll");
returnValue = Assembly.LoadFrom(executingAssemblyPath);
_assembliesResolved = true;
return returnValue;
}
return null;
}

You cannot catch exceptions generated by the fact that a refereced assembly was not found.
Only if you manually load the assembly with Reflection you could catch the exception.
To check if the sqlite assembly is there, do a File.Exists().

In the first case you cannot catch the exception because the jit throws the exception as soon as it hits the method. In the second case it jits your method and the exception is thrown by the time it tries to jit the DeclareConnection method.

Related

Append To Text File Each Error

I am using this syntax to write errors to a text file for logging in my Global.axax - it overwrites each time and only logs the most recent error. While this is helpful, it is not as helpful as I need it to be. How can I log each error that is raised?
This is my current code that only logs the most recent:
void Application_Error(object sender, EventArgs e)
{
Exception CurrentException = Server.GetLastError();
Server.ClearError();
if (CurrentException != null)
{
try
{
using (StreamWriter sw = new StreamWriter(Server.MapPath("HereAreErrors.txt")))
{
sw.WriteLine(CurrentException.ToString());
sw.Close();
}
}
catch (Exception ex) { }
}
}
As others have stated you're better off using an existing log tool to handle your logging. They have a myriad of features and, best of all, are maintained by someone else!
With that said, and in the interest of answering the question as asked, here's how to resolve your problem. It has the added benefit of creating the file if it doesn't exist.
void Application_Error(object sender, EventArgs e)
{
Exception CurrentException = Server.GetLastError();
Server.ClearError();
if (CurrentException != null)
{
try
{
File.AppendAllText(Server.MapPath("HereAreErrors.txt"), CurrentException.ToString());
}
catch (Exception ex) { }
}
}

How to capture the abscence of a library in Visual Studio?

I have developed a custom library that I use in some projects.
Nowadays I'm implementing the error capture in my application. One of them considers the possibility that the machine where I try to execute my application doesn't have my libraries.
So what I made to check if the library was installed or not, was try to use it surrounded with a try-catch clause like this:
try
{
MyLibrary library = new MyLibrary();
}
catch (Exception e)
{
MessageBox.Show("Your library is not installed");
Close();
}
This code should show a message when the library is not found, and then close my application. But the message is never shown.
Any idea on how to check if my library is not located in my machine?
With your current try-catch you can not catch that kind of exception because there are not related to your code. The Runtime will try to load the assembly, if it cannot be found, the AssemblyResolve event is raised.
class Test
{
public static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += MyResolveEventHandler;
}
private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
Console.WriteLine("Try resolving: " + args.Name);
return null;
}
}

Catch all exceptions in ASP.NET C# rather than each method in a `try{} catch{}` block

Is there a better way to catch all exceptions in one place without writing try{} catch{} for each method?
You can catch the exceptions in your application by overwriting Application_Error found in Global.asax. However, using this approach you cannot act on these exceptions like you could using a regular try catch block.
You can log it
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// if there's an Inner Exception we'll most likely be more interested in that
if (ex .InnerException != null)
{
ex = ex .InnerException;
}
// filter exception using ex.GetType() ...
// log exception ...
// Clear all errors for the current HTTP request.
HttpContext.Current.ClearError();
}
And/or redirect
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// process exception
// redirect
HttpContext.Current.ClearError();
Response.Redirect("~/Error.aspx", false);
return;
}
And this is about all your can do.
Thanks All. I got an answer from a site.Here is the code i have modified according to the exception and logging errors with a third party(Elmah) in the application. Hope, it will be helpful for others.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
//Get the exception object
Exception exceptionObject = Server.GetLastError();
try
{
if (exceptionObject != null)
{
if (exceptionObject.InnerException != null)
{
exceptionObject = exceptionObject.InnerException;
}
switch (exceptionObject.GetType().ToString())
{
case "System.Threading.ThreadAbortException":
HttpContext.Current.Server.ClearError();
break;
default:
// log exception ...
//Custom method to log error
Elmah.ErrorSignal.FromCurrentContext().Raise(exceptionObject);
break;
}
}
}
catch
{
//Avoiding further exception from exception handling
}
}

Throwing exception after modifying its Dictionary

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.

What happen if the code within a catch fails

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

Categories

Resources