Catching custom exception in c# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have created a custom exception class as below
namespace testingEXception
{
public class CustomException : Exception
{
public CustomException()
{
}
public CustomException(string message)
: base(message)
{
}
public CustomException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
I am throwing an exception from a different project in the same solution like this
namespace ConsoleApplication1
{
public class testClass
{
public void compare()
{
if (1 > 0)
{
throw new CustomException("Invalid Code");
}
}
}
}
and catching it like this
namespace testingEXception
{
class Program
{
static void Main(string[] args)
{
try
{
testClass obj = new testClass();
obj.compare();
}
catch (testingEXception.CustomException ex)
{
//throw;
}
catch (Exception ex)
{
// throw new CustomException(ex.Message);
}
Console.ReadKey();
}
}
}
The problem is, the exception is not getting caught by the first catch, but instead getting caught by the second catch, over though the type of exception shows CustomException.

You need to provide more detail, the following code outputs "CustomException":
try
{
throw new CustomException("Invalid code.");
}
catch (CustomException ex)
{
System.Diagnostics.Trace.WriteLine("CustomException");
throw;
}
catch (Exception ex)
{
throw;
}
With the following class:
public class CustomException : Exception
{
public CustomException()
{
}
public CustomException(string message)
: base(message)
{
}
public CustomException(string message, Exception innerException)
: base(message, innerException)
{
}
}
Update:
With regard to optimizations and optimizing away a throw: this cannot happen because any particular block of code cannot know whether a caller higher up in the stack could have code to catch CustomException. Throwing an exception is a visible side-effect and there are various guarantees in the CLI to ensure those visible side-effects remain visible.
In addition, try, catch and finally blocks are "protected regions" in CLI-speak. These regions are special in that the operations within the region with "visible" side-effects cannot have their visible side-effects re-ordered. For some more detail, see http://lynk.at/qH8SHk and http://lynk.at/pJcg98

Related

Problem with Exception.Cannot print exception string because Exception.ToString() failed

I am currently practicing creating my Exception class. The idea of this code is for the user to enter a password. In case its code is less than 5 characters, the program will throw an exception. I want that my program throw one exception with text("Password is too small") and the object of my Exception class use ToString method(where will write " Password Length Exception").What confuses me is why I get the message Unhandled exception.Password Length exception. Cannot print exception string because Exception.ToString () failed. You can see this in the photo
Here is my code.
public class My_Exception : Exception
{
public My_Exception(string message) : base(message)
{
Console.WriteLine(message);
}
public override string ToString()
{
throw new My_Exception(" Password Length exception ");
}
}
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter your password");
string Password = Console.ReadLine();
if (Password.Length < 5)
{
throw new My_Exception(" Password is too small ");
}
}
catch(My_Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
Remove the override .ToString().
public class My_Exception : Exception
{
public My_Exception(string message) : base(message)
{
Console.WriteLine(message);
}
}
The message will be shown by the base Exception.ToString(). You shouldn't thow an exception from another exception.
And in truth, you shouldn't Console.WriteLine() from inside the constructor of an Exception. It is the try/catch block that should print in any way it wants the exception.
public class My_Exception : Exception
{
public My_Exception(string message) : base(message)
{
}
}
See running example at https://ideone.com/FchSGc
Don't throw an exception in the .ToString method. Return a string with information about what happened.
public override string ToString()
{
return " Password Length exception ";
}
Or simply create a proper exception
public class PasswordToSmallException : Exception
{
public PasswordToSmallException()
: base("Password should be at least 5 characters")
{}
}
And then you just
catch(Exception ex)
{
Console.WriteLine(ex);
}
Problem : cannot print exception string because exception.tostring() failed
Solution : I think it is a problem with the computer. I had this message also. I just restart the computer and it work.

Can't catch exception thrown in derived class

Why base class's try-catch doesn't catches exception thrown in derived class?
Did I missed something?
Base class:
public class UmBase
{
protected Thread ThisThread;
protected UmBase(int cycleMs, UpdateManager updateManager,
string loggerFilename, string loggerFolder = "UpdateManager")
{
}
public void Start()
{
ThisThread = new Thread(Work);
ThisThread.Start();
}
public virtual void Iteration()
{
throw new Exception("Iteration Method should be overidden!");
}
public void Work()
{
while (IsProcessing)
{
try
{
Iteration();
}
catch (Exception exception)
{
Log.Error(exception.Message); //WANT TO HANDLE IT HERE
}
finally
{
Sleep(100);
}
};
}
}
Derived class:
public class ReadParams : UmBase
{
public ReadParams(UpdateManager updateManager, int cycleMs = 60000)
: base(cycleMs, updateManager, "sss")
{
Iteration();
}
public override void Iteration()
{
try
{
DbParams.Set(); //EXCEPTION IS THROWN INSIDE
}
catch (Exception exception)
{
throw new Exception("Oops!", exception);
}
}
}
I've read here Can we catch exception from child class method in base class in C#? and can't find my mistake.
Try/Catch will only catch exceptions thrown in the try block. That includes any exceptions thrown by other methods called within the try block. Have you got exceptions configured to break on just unhandled or also on thrown? See here for how to configure exception breaks
The other possibility is that your exception is being thrown at time of object construction, because your ReadParams constructor calls Iteration() without a try/catch.
i.e.
public class ReadParams : UmBase
{
public ReadParams(UpdateManager updateManager, int cycleMs = 60000)
: base(cycleMs, updateManager, "sss")
{
Iteration();
}
public override void Iteration()
{
try
{
// If throw here (A)
DbParams.Set(); //EXCEPTION IS THROWN INSIDE
}
catch (Exception exception)
{
// I'll catch here (A) and then throw a new exception
throw new Exception("Oops!", exception);
}
}
}
public void Work()
{
while (IsProcessing)
{
try
{
// Exceptions thrown here including the one you
// threw in the method Iteration (B)
Iteration();
}
catch (Exception exception)
{
// Will be caught here (B)
Log.Error(exception.Message); //WANT TO HANDLE IT HERE
}
finally
{
Sleep(100);
}
};
}
If I read it right, the sequence is:
ReadParams ctor
UmBase ctor
ReadParams Iteration
ReadParams Iteration throw new Exception("Oops!", exception);
Crash... because there is no try-catch in ReadParams ctor
When you override a method you actually replace the entire method wholesale as far as instances of the derived class is concerned.
Unless you call the inherited method explicitly from the overridden one, it is not part of your derived class's logic.
I faced same problem .I noticed one thing but not sure of the reason.
When u inherit a base class privately its catch block does not catch the exception of the derived class.
inherit the base class publicly and give it a try.

Why is custom exception changed to System.Exception when method invoked via method.invoke()?

I've written a custom exception AbortTestException, which is pretty simple:
class AbortTestException : Exception
{
public AbortTestException(string message)
: base(message) { }
}
Then I have a function that will throw it:
class Foo
{
public void Throws()
{
throw new AbortTestException("hi");
}
}
And Throws() gets called via method reference:
class Program
{
static void Main(string[] args)
{
Type myType = (typeof(Foo));
var method = myType.GetMethod("Throws");
try
{
method.Invoke(new Foo(), null);
}
catch (AbortTestException ex)
{
Console.WriteLine("AbortTestException");
}
catch (Exception ex)
{
Console.WriteLine("Exception");
}
}
}
However, something weird happens. Even though Throws rises an AbortTestException, the catch(Exception) block gets used (instead of the catch(AbortTestException) block). I tried putting the "throw new AbortTestException("hi")" portion in the try block itself, and verified that the correct catch block is used.
Is there some reason an exception would be re-cast when emitted via MethodInfo.invoke()?
http://msdn.microsoft.com/en-us/library/4k9x6bc0.aspx
Per the MSDN a TargetInvocationException is thrown if the invoked method or constructor throws an exception.
Did you check the nested Exception? My guess the original exception (AbortTest...) is wrapped in a nested one. The nested Exception will be in the InnerException property of the one which is caught by your code
Remember that catching Exception will match any exception that isn't caught by a more specific catch block before it:
Type myType = (typeof(Foo));
var method = myType.GetMethod("Throws");
try
{
try
{
method.Invoke(new Foo(), null);
}
catch (AbortTestException ex)
{
Console.WriteLine("AbortTestException");
}
catch(TargetInvocationException tie)
{
throw tie.InnerException;
}
catch (Exception ex)
{
Console.WriteLine("Exception");
}
}
catch(AbortTestException ate)
{
Console.WriteLine("AbortTestException after re-throw from TargetInvocationException");
}

How can I throw an exception and add in my own message containing a key and a value?

I have methods that look like this:
public IDictionary<string, string> Delete(Account account)
{
try { _accountRepository.Delete(account); }
catch { _errors.Add("", "Error when deleting account"); }
return _errors;
}
public IDictionary<string, string> ValidateNoDuplicate(Account ac)
{
var accounts = GetAccounts(ac.PartitionKey);
if (accounts.Any(b => b.Title.Equals(ac.Title) &&
!b.RowKey.Equals(ac.RowKey)))
_errors.Add("Account.Title", "Duplicate");
return _errors;
}
I would like to change this method so that it returns a bool and so it throws an exception if there is an error instead of:
_errors.Add("", "Error when deleting account");
Can someone explain to me how I can throw an exception and pass a message containing a key and a value. In this case the key would be "" and the value would be "Error when deleting account".
Also in the method that calls this. How would I catch the exception?
Would it be necessary for me to make my own class and somehow throw an exception based on this class?
Create your own exception class, that can hold the data that you need:
public class AccountException : ApplicationException {
public Dictionary<string, string> Errors { get; set; };
public AccountException(Exception ex) : base(ex) {
Errors = new Dictionary<string, string>();
}
public AccountException() : this(null) {}
}
In your methods you can throw the exception. Don't return an error status also, that is handled by the exception.
Don't throw away the exception that you get in the method, include that as InnerException, so that it can be used for debugging.
public void Delete(Account account) {
try {
_accountRepository.Delete(account);
} catch(Exception ex) {
AccountException a = new AccountException(ex);
a.Errors.Add("", "Error when deleting account");
throw a;
}
}
public void ValidateNoDuplicate(Account ac) {
var accounts = GetAccounts(ac.PartitionKey);
if (accounts.Any(b => b.Title.Equals(ac.Title) &&
!b.RowKey.Equals(ac.RowKey))) {
AccountException a = new AccountException();
a.Errors.Add("Account.Title", "Duplicate");
throw a;
}
}
When calling the methods, you catch your exception type:
try {
Delete(account);
} catch(AccountException ex) {
// Handle the exception here.
// The ex.Errors property contains the string pairs.
// The ex.InnerException contains the actual exception
}
The Exception class has a Data property that is a dictionary of key/value pairs.
IDictionary<string, string> errors;
...
if (errors.Count > 0)
{
Exception ex = ... construct exception of the appropriate type
foreach(string key in _errors.Keys)
{
ex.Data.Add(key, _errors[key]);
}
throw ex;
}
Note that it's generally considered to be good practice to use Exceptions that are Serializable, so that the objects you put into the Data dictionary should also be serializable. In your example, you're just putting in strings, so you'll be fine.
Would it be necessary for me to make my own class and somehow throw an exception based on this class?
It's certainly not necessary to create your own custom Exception class, and may not be desirable. The MSDN design guidelines for Exceptions gives guidelines on choosing which Exception type to throw.
In general, you should prefer to use one of the existing Exception types unless you have an error condition that can be programatically handled in a different way from existing Exception types.
Create your own Exception and then throwing it.
public class RepositoryException : Exception
{
public RepositoryException() : base()
{
}
public RepositoryException(string key, string value) : base()
{
base.Data.Add(key, value);
}
public RepositoryException(string message) : base(message)
{
}
public RepositoryException(string message, Exception innerException) : base(message, innerException)
{
}
}
public Boolean Delete(Account account)
{
try
{
_accountRepository.Delete(account);
return true;
}
catch (Exception ex)
{
throw new RepositoryException("", "Error when deleting account");
// throw new RepositoryException("Error when deleting account", ex);
// OR just
// throw new RepositoryException("Error when deleting account");
}
}
You could throw your own exceptions instead of
_errors.Add("", "Error when deleting account");
So every _errors.Add(..) will be replaced with something like
throw new MyAppException(key, value);
How to create your own exception class was explained above. So you supply your exception object with key and value.
You should know which exception type you're going to catch
try {
Delete(account);
} catch(NullPointerException ex) {
throw new MyAppException(key, value);
}
And now in your caller-methods(outer-methods) you can catch only your exceptions.
try {
_accountRepository.Delete(account);
} catch(MyAppException ex) {
//exception handle logic
}

exception derived from system.exception thrown but not caught

I am using the following system.exception derived exception in the following manner and would expect the exception thrown in SomeFunction to be caught in the catch block in SomeOtherFunction but instead I receive an unhandled exception error when the code attempts to throw the exception, any insight would be appreciated.
void SomeFunction()
{
if (someValue == false)
{
throw(new MyException("some error, falseValue,null);
}
}
void SomeOtherFunction()
{
try
{
SomeFunction();
}
catch(MyException ex)
{
}
}
public class MyException : Exception
{
public MyException (string message, Reason reason, Exception innerException)
: base(message, innerException)
{
Reason = reason;
}
public Reason Reason { get; private set; }
}
There must be other code that is contributing to this issue - here is a complete example that works:
using System;
class Example
{
static void Main()
{
SomeOtherFunction();
}
static void SomeFunction()
{
throw new MyException("some error");
}
static void SomeOtherFunction()
{
try
{
SomeFunction();
}
catch (MyException)
{
Console.WriteLine("caught the exception");
}
}
}
class MyException : Exception
{
public MyException(string message)
: base(message) { }
}
Perhaps you can use this example and work backwards to see if there is something missing from your real code? Since there were compilation issues with your examples I am assuming that you have sanitized some production code.
I see some minor syntax errors. But I think your unhandled exception error might be coming from the constructor of MyException or the way you're handling Reason in your constructor/get,set methods. It seems like you're trying to set a value to a class, but I'm still trying to migrate from c++..so idrk what im talking about.
Try fixing syntax and working with your "Reason"

Categories

Resources