I want to convert a string into exception but not able to find any thing on google.
I am using C# .Net 2.0.
Reason is because third party client has a method that is logging method and only takes exception and i have a scenario where i must need to log something but using that method. so must need to convert string into exception.
Exceptions are created as any other object, using the new keyword. You can provide it a message argument that you can store your string in:
Exception e = new Exception("Your string goes here");
If you are using Try...Catch() then you can do following to add your customize message and original exception together
try{
//your code block
}
catch(Exception e)
{
var exception = new Exception("Your message: ");
//Display "exception" to users
//Log "e" for further investigation
}
Related
I have a function "ReturnString":
public static string ReturnString(string sa, string sb)
{
try
{
...
...
return "xyz";
}
catch (Exception ex)
{
throw new clsException(ex.Message);
}
}
it is call by more than 600 times from other more then 40 classes and win farms Mean's it has more than 600 references in more then 40 classes and win farms.
When Exception thrown by it, I want to know what is the it's last calling ref. when exception happen?
Please help me to solve this without changing function arguments.
You should initialize an instance of StackTrace class -
https://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace(v=vs.110).aspx
Then, get the first StackFrame -
https://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe(v=vs.110).aspx
Finally, get the MethodBase of this frame; Its "Name" property is what you need -
https://msdn.microsoft.com/en-us/library/system.reflection.methodbase(v=vs.110).aspx
Try this:
public static string ReturnString(string sa, string sb)
{
try
{
//...
//...
return "xyz";
}
catch (Exception ex)
{
StackTrace oStackTrace = new StackTrace();
string sMethodName = oStackTrace.GetFrame(1).GetMethod().Name;
//It's not a good practice to keep only the error message (you may need other exception details later)
throw new clsException(string.Format("{0}: {1}", sMethodName, ex.Message));
}
}
Your problem is here:
throw new clsException(ex.Message);
As others have mentioned, ex already contains the info you want inside the StackTrace property (check this link for more info).
But when you throw a new exception, you are only throwing the message, and ignoring all the info you want to get.
Just throw without a new exception, or include ex as the inner exception of your clsException.
I want to know what is the it's last calling ref. when exception
happen?
Then check the exception StackTrace, that will let you know the entire call stack and the latest one responsible for exception. Also the innerException property if any.
Check the documentation on Exception class. It has a property StackTrace which you should check.
In your case, the exception object should have it ex.StackTrace
You may also want to get the TargetSite property value from your exception object saying ex.TargetSite
I have seen similar questions, but not exactly this:
I would like to know the right way of determining whether a method is executed correctly or not, returning a boolean, and if the method is not executed know the reason, even if an exception is thrown.
I do it in this way, but I think that return inside the catch is a bad practice, so which is the right way?:
if(!myObject.DoSomething('A', out result))
{
MessageBox.Show(myObject.ErrorMessage);
[...]
}else{
MessageBox.Show(result);
[...]
}
class myObject()
{
public string ErrorMessage;
bool DoSomething(char inputValue, out string result)
{
try
{
if(inputValue == 'A')
{
ErrorMessage = "Bad input value: " + inputValue;
return false;
}
[...]
return true;
}catch(Exception ex){
ErrorMessage = ex.Message;
return false;
}
}
I don't like trhow the exception inside the catch because I lose the control of the application (and I can't get the description), and the exception always finish in the form. And if I show the exception in the form, I don't need try catch in the rest of the classes.
I mean that try {} catch(Exception ex) { throw ex;} is the same as not putting try catch.
thanks a lot
My suggestion would be to create your own Exception type (possibly global), and pass it in as a reference.
Thereafter you can still get back your boolean indicating success or failure (and having only one return outside of the try..catch).
public class CustomException
{
private string _message;
private string _title;
public CustomException()
{
_title = "";
_message = "";
}
public CustomException(string title, string message)
{
_title = title;
_message = message;
}
}
Then call DoSomething passing in an instance of CustomException (ce in this case).
CustomException ce = new CustomException();
Be advised this is the best process to solve the problem of having to return a boolean indicating success or failure and know the message, for example; dumping it to a log file or logging to database (particularly for Service Calls - WCF)
However this is not a solution for bad logic in handling business process.
Return false inside a catch isn't by itself bad practice. It's useful when you handle a piece of code's exceptions and it must not fail.
For example, I'm working on a printer piloting DLL at the time, and this DLL must read a XML file containing multiple records to print. The method must not fail because one record fails to print, but it still can return exception if the XML file is not correctly formated.
public void Print(string xmlFile)
{
if (String.IsNullOrWhiteSpace(xmlFile))
throw new ArgumentNullException("No xml file has been passed to the Print method.");
// This line will most likely throw an exception if the XMl file is not well formated
XDocument dom = XDocument.Load(xmlFile);
foreach (XElement n in dom.XPathSelectElements("//RECORDS/RECORD"))
{
try
{
// send commands to the printer, if the printer fails to print, throw a PrinterRecordException
}
catch (PrinterRecordException e)
{
// log print failure, but keep on printing the rest
continue;
}
catch (Exception e)
{
// dunno what happened, but still have to print the rest
continue;
}
}
}
In this example, my function could return false instead of throwing exceptions to the main program, if this program doesn't care. In my case it does :p In my opinion, that's how you should think your method.
Exception handling methods and best practices are a some-what subjective matter. I cannot attest to the method I'm about to present because I have only just started to use it in my own project.
What I suggest is having a static ExceptionHandler class with which you can register any exception to be handled by Generic Parameter and its corresponding handler. This will decouple your business logic from your UI in case you wanted to display some kind of message box when a particular exception occurs.
Here's an example:
/// the real implementation uses lambda's and/or implementations of IExceptionHandler<TException>
ExceptionHandler.Register<InvalidPasswordException>(() => /*some handler logic*/);
// ... else where in the code ...
catch (InvalidPasswordException ex)
{
// do resource clean-up and raise exception for listeners such as the UI or logging infrastructure.
ExceptionHandler.Raise(ex);
}
So far this looks promising, especially when compared with my previous approaches. But only time will tell.
Update
The ExceptionHandler class itself need not be static, for example you might want to have different instances of ExceptionHandlers at different layers of your application if you are using a layered architecture.
This comes from a book but won't debug with correct message in my Visual Studio 2010, it just gives me Unhandled exception at throw new ApplicationException("Smth. bad happened", e);
Is there an error in the book or is it my VS2010 exception settings maybe? The console output is supposed to show that given the file does not exist the inner and outer trace will be printed along with File Not Found. Does it have to do with Just-in-time debugging?
Current Output:Unhandled Exception.........................................................
Desired output:http://www.introprogramming.info/wp-content/uploads/2013/07/clip_image008.png
class program
{
static void Main()
{
try
{
string fileName = "WrongFileName.txt";
ReadFile(fileName);
}
catch (Exception e)
{
throw new ApplicationException("Smth. bad happened", e);
}
}
static void ReadFile(string fileName)
{
TextReader reader = new StreamReader(fileName);
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();
}
}
If you want to wrap an exception in your own and have it bubble up, you should remove the inner try, since every try needs a matching catch. Since you're wrapping an exception of your own with the original exception, it doesn't serve any purpose if you are immediately catching it.
try
{
string fileName = "WrongFileName.txt";
ReadFile(fileName);
}
catch (Exception e)
{
throw new ApplicationException("Smth. bad happened", e);
}
EDIT:
This is expected behavior. You're explicitly throwing an exception, and no one is handling it. The book is likely trying to make the point that you can wrap exceptions to provide additional information, while still preserving the original exception. Check to ensure that the file you're trying to open is in the right place.
As an additional note, you should really wrap the file stream in a using block to ensure that the underlying handles/resources are closed.
static void ReadFile(string fileName)
{
using (TextReader reader = new StreamReader(fileName))
{
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();
}
}
You have to make sure that you the file "WrongFileName.txt" is in your project's Bin/Debug folder (you include the file in the project and set it's build action to Content and Copy always, if you want it not to throw the exception.
I presume that the book was trying to show, that when the file name is correct, the program will go through normally, but otherwise will cause error.
The catch block gets run because the file doesn't exist in this case and therefore the action inside is executed. This concrete action is to throw the exception again but with more helpful information. You can also see, that this new exception's constructor accepts the original exception as the second parameter, which means it will be included in this exception's InnerException property.
In my C# project, I'm using System.Data.SQLite.dll downloaded from CodeProject.
My problem is as per the title - how to get the error codes after calling SqliteCommand.ExecuteNonQuery() function?
Error codes such as SQLITE_CONSTRAINT, SQLITE_BUSY, SQLITE_LOCKED as shown here.
use the Exception.StackTrace or the SQLiteException.ErrorCode
try
{
}
catch(SQLiteException ex)
{
string code = ex.ErrorCode;
}
I'm going to add to this to help others, if you're developing in .NET. Use the
SQLiteErrorCode enumeration to test the result, cast the ErrorCode:
try
{
}
catch(SQLiteException ex)
{
SQLiteErrorCode sqlLiteError= (SQLiteErrorCode)ex.ErrorCode;
//Do whatever logic necessary based of the error type
}
Good question.
System.Exception does not have a member by the name ".ErrorCode"
Catch Ex As SQLiteException
E = Ex.ResultCode
Return E
End Try
So, I have a list containing a custom class, MyClass
MyClass has properties, which can be null (but aren't meant to be).
When this class is sorted, using a custom sorter, where the sorter accesses this null property and throws an exception, the exception is considered unhandled, even though there is a try-catch block around the sort method.
Now for some reason the exception still gets written to the console, which is what the exception handler is doing.
I have a real application with this same issue, causing my unit tests to fail, even though the exception is handled correctly and I cannot explain this.
So I have attached some sample code to explain myself better, run this from VS.
Updated Code
Results:
System.InvalidOperationException
Failed to compare two elements in the array.
Done!
So it seems to be handling my custom exception, and throwing its own?
using System;
using System.Collections.Generic;
using System.Data;
namespace TestSortException
{
class Program
{
static void Main()
{
try
{
var list = new List<MyClass>
{
new MyClass("1"),
new MyClass(null),
new MyClass("fdsfsdf")
};
list.Sort(new MyClassSorter());
}
catch(Exception e)
{
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message);
}
Console.WriteLine("Done!");
Console.ReadLine();
}
}
class MyClassSorter : IComparer<MyClass>
{
public int Compare(MyClass x, MyClass y)
{
// try
// {
if (x.MyString == y.MyString)
return 0;
// Unhandled??? Exception here
if (x.MyString.Length > y.MyString.Length)
return 1;
return -1;
// }
// catch (Exception)
// {
// return -1;
// }
}
}
class MyClass
{
private string _myString;
public string MyString
{
get
{
if (_myString == null) throw new DataException("MyString is Null");
return _myString;
}
}
public MyClass(string myString)
{
_myString = myString;
}
}
}
There's a try/catch block round the Sort method, yes - and that catch block catches the exception. In other words, Sort throws an exception and your catch block catches it. It doesn't propagate out beyond Main - so "Done!" is printed.
This is exactly what I'd expect. In what way is it "unhandled" in your experience? Were you expecting Sort not to throw the exception? It needs to do something to indicate the failure to compare two elements, and this seems to be the most appropriate course of action.
In what way are your unit tests failing? Are you deliberately giving them invalid data? How do you want your comparison code to react to invalid data? If it should ignore it (and return a comparison based on another property), then you should actively check the property rather than letting an exception propagate. In most cases I'd rather allow the exception if this indicates that there's a bug earlier on though.
EDIT: Based on your other comments, it sounds like you're doing the appropriate thing, letting the exception bubble up - but it's not clear in what way you're seeing the exception not be handled.
If you're running in the debugger, it may be breaking on the exception being thrown, but that doesn't mean it won't be handled. Try either changing your exception settings or running without the debugger.
EDIT: Yes, Sort will catch the exception and throw an InvalidOperationException instead - but you can use the InnerException property of that exception to get hold of the original one. It's unfortunate that the documentation doesn't specify this :(
For example, when it checks that string "1" isn't equal to null. But it wants then to compare lengths of "1" string and null => which is impossible.
I assume you work with .Net Framework 4.0. The new thing there is that a NullRefenrenceException can not be caught any more (similar to OutOfMemory exception).