we have 2 custom class (baseClass and ChildClass) the child class has inherited from the baseClass
when we get a exception on childClass, OnException event on the baseClass should be called
it'll be like MVC Controller OnException Events
We will use for logging.
In the general case it is not possible to do. The MVC OnException works because the framework catches any unhandled exceptions and forwards them to OnException. The framework code for calling a controller action is something like:
try
{
controller.SomeAction();
}
catch(Exception ex)
{
controller.OnException(ex);
}
The entire implementation depends on the caller of the code taking the responsibility to handle the exceptions. With a general calls that can be used by any code you can't make any assumptions on how the class will be called.
If we somehow can make all calls go through the base class we can make something similar:
public class Base
{
public BlahaMethod()
{
try
{
DoBlaha();
}
catch(Exception ex)
{
OnException(ex);
}
}
protected abstract void DoBlaha();
private void OnException(Exception ex)
{
// Handle exception
}
}
public class Derived
{
protected virtual void DoBlaha()
{
throw new NotImplementedException();
}
}
You can catch exception with a try-catch-finally construct. The only general exception handler (known to me) is the unhandled exception handler in the appdomain.
Related
Is it necessary to declare a class in 'public ' visibility mode if the class is defining the user defined exception which extends System.exception class in C#?
It entirely dependes on how you want to use your user defined exception class.
The concept of access modifier is not related at all with the idea of a user defined exception.
A user defined exception is just a user defined class which extends System.Exception, while an access modifier is a construct which specifies the visibility of that class with respect to the client code.
This means that if you just want to use your custom exception class inside the defining assembly you can simply define it as an internal class.
Of course this won't be very useful, because you usually define custom exception class inside class libraries and you want them to be visible in any assembly referencing your class library, so that a consumer can have a chance to handle your custom exception class if it makes sense in his or hers client code.
Try it on DotNetFiddle and see:
public class Foo
{
private class MyException : Exception
{
public MyException(string message) : base(message) { }
}
public static void Throw()
{
throw new MyException("Hello world.");
}
}
public class Program
{
public static void Main()
{
try
{
Foo.Throw();
}
//catch(Foo.MyException myException)
//{
// This doesn't compile
//}
catch(System.Exception exception)
{
Console.WriteLine
(
"Exception is of type '{0}' with a message of '{1}'",
exception.GetType().Name,
exception.Message
);
//Does not compile:
//var typedException = (Foo.MyException)exception;
}
}
}
Output:
Exception is of type 'MyException' with a message of 'Hello world.'
So it turns out you can still catch the exception, inspect its type, and read its base properties, and everything works. But if you want to handle it in a type-safe way and cast it to the specific type, your code won't compile. This also means you can't use a type-specific catch handler.
I have simple controller with one dependency
public TestController(ITestFacade testFacade)
{
_testFacade = testFacade;
}
and simple facade
public class TestFacade : ITestFacade
{
public TestFacade()
{
throw new Exception("Test");
}
}
I have Unity resolver and registration
public static void RegisterDependencies(IUnityContainer container)
{
container.RegisterType<ITestFacade, TestFacade>();
}
UnityResolver is common as found everywhere. Nothing custom.
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
// Here in one of Inner Exceptions is my Facade exception, but I want to get it later
return null;
}
}
Please consider this as test scenario. Facade in constructor should fail for any reason. It is not important now.
Running application results in exception:
An error occurred when trying to create a controller of type 'TestController'. Make sure that the controller has a parameterless public constructor.
Ok, this is because of error in constructor of Facade when resolver is not able to get instance and activator in controller failed.
My question is - is there any way how to catch this exception in IHttpControllerActivator or somewhere?
I can try catch code in Facade constructor and log it somehow, but why this exception is ignored after resolver.
I am writing a method in c# class as shown below:
using(sftpClient)
{
sftpClient.Connect();
try{
//Do some process
}
catch(Exception ex)
{
}
sftpClient.Disconnect();
}
I need to create some more methods similar to the above but the logic changes only inside the try{} catch{} block. Can anyone suggest some best way to achieve this using some design pattern?
You could create an abstract base class:
abstract class MyBaseClass {
protected abstract void DoSomething();
public void DoSmtpStuff() {
smtpClient.Connect();
try {
DoSomething();
} catch (Exception ex) {
}
smtpClient.Disconnect();
}
}
and then just create inheritances of that class, which implement only the DoSomething method.
Take a look at the Strategy Pattern (emphasis my own):
In computer programming, the strategy pattern (also known as the
policy pattern) is a software design pattern that enables an
algorithm's behavior to be selected at runtime.
So basically, you would declare an interface, say, IBehaviour and define some method:
public interface IBehaviour
{
void Process();
}
Then have a different class implement IBehaviour for each piece of logic you want to have.
The class where you need to consume the logic would then allow passing an IBehaviour object and in your try block just do behaviour.Process().
This will allow you to set up the behaviour from outside the class and then simply pass it along to the class in which you want to actually do something with it.
Alternative to classes is just take Action as argument:
TResult WithSftpClient<TResult>(Func<TResult, SftpClient> operation)
{
TResult result = default(TResult);
// Note that one may need to re-create "client" here
// as it is disposed on every WithSftpClient call -
// make sure it is re-initialized in some way.
using(sftpClient)
{
sftpClient.Connect();
try
{
result = operation(sftpClient);
}
catch(Exception ex)
{
// log/retrhow exception as appropriate
}
// hack if given class does not close connection on Dispose
// for properly designed IDisposable class similar line not needed
sftpClient.Disconnect();
}
return result;
}
And use it:
var file = WithSftpClient(client => client.GetSomeFile("file.name"));
You can use this pattern:
abstract class ProcedureBase<T>
{
public T Work()
{
using(sftpClient)
{
sftpClient.Connect();
try{
ProtectedWork();
}
catch(Exception ex)
{
}
sftpClient.Disconnect();
}
}
protected abstract T ProtectedWork();
}
class Procedure1 : ProcedureBase<TypeToReturn>
{
protected override TypeToReturn ProtectedWork()
{
//Do something
}
}
class Procedure2 : ProcedureBase<AnotherTypeToReturn>
{
protected override AnotherTypeToReturn ProtectedWork()
{
//Do something
}
}
Usage:
static void Main(string[] args)
{
Procedure1 proc = new Procedure1();
proc.Work();
}
I have a following C# scenario-
I have to handle an exception in base class that actually occurs in the derived class.
My base class looks like this:
public interface A
{
void RunA();
}
public class Base
{
public static void RunBase(A a)
{
try
{
a.RunA();
}
catch { }
}
}
The derived class is as follows:
public class B: A
{
public void RunA()
{
try
{
//statement: exception may occur here
}
catch{}
}
}
I want to handle the exception, lets say exception C, that occurs in B(at //statement above).
The exception handling part should be written in base class catch inside RunBase. How can this be done?
public class Base
{
public static void RunBase(A a)
{
try
{
a.RunA();
}
catch(SomeSpecialTypeOfException ex)
{
// Do exception handling here
}
}
}
public class B: A
{
public void RunA()
{
//statement: exception may occur here
...
// Don't use a try-catch block here. The exception
// will automatically "bubble up" to RunBase (or any other
// method that is calling RunA).
}
}
How can this be done?
What do you mean? Just remove the try-catch block from RunA.
Having said that, you need to make sure Class A knows how to handle the exception, this includes streamlining it to UI, logging, ... This is in fact rare for a base class. Handling exception normally happen at the UI level.
public class B: A
{
public void RunA()
{
try
{
// statement: exception may occur here
}
catch(Exception ex)
{
// Do whatever you want to do here if you have to do specific stuff
// when an exception occurs here
...
// Then rethrow it with additional info : it will be processed by the Base class
throw new ApplicationException("My info", ex);
}
}
}
You also might want to throw the exception as it is (use throw alone).
If you dont need to process anything here, dont put try{} catch{}, let the exception bubble up by itself and be processed by the Base class.
Just remove the try catch from class B, if the exception occurs it will propergate up the call chain until it is handled. In this case you can handle the exception in RunBase using your existing try catch block.
Though in your example B isn't derived from your base class Base. If you really want to handle a situation where an exception is thrown in a derived class in its parent you could try something like:
public class A
{
//Public version used by calling code.
public void SomeMethod()
{
try
{
protectedMethod();
}
catch (SomeException exc)
{
//handle the exception.
}
}
//Derived classes can override this version, any exception thrown can be handled in SomeMethod.
protected virtual void protectedMethod()
{
}
}
public class B : A
{
protected override void protectedMethod()
{
//Throw your exception here.
}
}
I would like to automagically add the following code around the body of some methods:
try
{
// method body
}
catch (Exception e)
{
throw new MyException("Some appropriate message", e);
}
I am working with PostSharp 1.0 and this is what I've done at the moment:
public override void OnException(MethodExecutionEventArgs eventArgs)
{
throw new MyException("Some appropriate message", eventArgs.Exception);
}
My problem is that I can see the PostSharp OnException call in the stack.
What would be the good practice to avoid this and get the same call stack as implementing by hand the exception handler?
There is no way to hide "OnException" from the call stack.
Two things working in tandem will allow you to do this:
The fact that Exception.StackTrace is virtual
The use of the skipFrames parameter to the StackFrame constructor. This is not required, but makes things easier
The below example demonstrates how to customize the stack trace. Note that I know of no way to customize the Exception.TargetSite property, which still gives the details of the method from which the exception originated.
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// exception is reported at method A, even though it is thrown by method B
MethodA();
}
private static void MethodA()
{
MethodB();
}
private static void MethodB()
{
throw new MyException();
}
}
public class MyException : Exception
{
private readonly string _stackTrace;
public MyException()
{
// skip the top two frames, which would be this constructor and whoever called us
_stackTrace = new StackTrace(2).ToString();
}
public override string StackTrace
{
get { return _stackTrace; }
}
}
}