public class MemberBAL : Members
{
private Member_DAL member;
public MemberBAL()
{
member = new Member_DAL(this);
}
public void MemberInfo()
{
try
{
member.GetMemberInfo();
}
catch (Exception err)
{
throw new Exception("Connection Failed.");
}
}
}
The code, at first glance, seems technically correct.
However, without any explanation of your problem, or what you're trying to achieve, that's about all I can say.
Related
using System;
// Custom Exception types
class AException : Exception
{
}
class BException : Exception
{
}
class Test
{
public static void Main(string[] args)
{
try
{
throw new AException();
}
catch (Exception ex)
{
Callme(ex);
}
}
public static void Callme(AException aexception) {}
public static void Callme(BException bexception) {}
public static void Callme(Exception ex) {}
}
Callme(ex) will always call Callme(Exception ex) instead of Callme(AException ..) .. Is this an expected behavior. I read method overload resolution do work with inheritance relationships.
there is a more accepted way of doing this. try the following:
try
{
throw new AException();
}
catch (AException aex)
{
Callme(aex);
}
catch (BException bex)
{
Callme(bex);
}
catch (Exception ex)
{
Callme(ex);
}
This question already has answers here:
Is there a way to catch all unhandled exceptions thrown by a given class?
(6 answers)
Closed 8 years ago.
I have a lot of classes (WCF services) that contain several function. Now I need to handle errors, but I don't want to create a block try ... catch within each function (for error handling).
How can I make try...catch in any class (or something else) so that we catch errors but did not write the same block within each method?
There will always be some duplication of code but you can reduce it to one line
public static class ExceptionHandler
{
public static void Run(Action action)
{
try
{
a();
}
catch(Exception e)
{
//Do Something with your exception here, like logging
}
}
}
and then just call
ExceptionHandler.Run(yourAction);
you can add overloads for functions and what not but this approach is not ideal. As you may want to catch specific exceptions in certain cases.
Since you did not provide code specifically, I will write some sample code to make it more obvious. If you have this:
public class MyClass
{
public void Method1ThatCanThrowException()
{
try
{
// the Method1 code that can throw exception
}
catch (MySpecificException ex)
{
// some specific error handling
}
}
public object Method2ThatCanThrowException()
{
try
{
// the Method2 code that can throw exception
}
catch (MySpecificException ex)
{
// the same specific error handling
}
}
}
So, if you intend to have single place error handling, you can use lambda, and the help of a private method:
private T CheckAndCall<T>(Func<T> funcToCheck)
{
try
{
return funcToCheck();
}
catch (MySpecificException ex)
{
// the old specific error handling
}
}
Notice the use of the Func<T> delegate. This is because you may need to wrap the try-catch logic around some code that can return a value.
Then you can rewrite the above methods like this:
public void Method1ThatCanThrowException()
{
CheckAndCall(
() =>
{
// the Method1 code that can throw exception
return null;
});
}
public object Method2ThatCanThrowException()
{
return CheckAndCall(
() =>
{
// the Method2 code that can throw exception
return someObject;
});
}
For example, rather than having to do this:
public class Program
{
public static string ReadFile(string filename)
{
//A BCL method that throws various exceptions
return System.IO.File.ReadAllText(filename);
}
public static void Main(string[] args)
{
try
{
Console.Write(ReadFile("name.txt"));
}
catch (Exception e)
{
Console.WriteLine("An error occured when retrieving the name! {0}", e.Message);
}
try
{
Console.Write(ReadFile("age.txt"));
}
catch (Exception e)
{
Console.WriteLine("An error occured when retrieving the age! {0}", e.Message);
}
}
}
You could implement a "Try..." method, using the ref or out keyword as appropriate:
public class Program
{
public static bool TryReadFile(string filename, out string val)
{
try
{
val = System.IO.File.ReadAllText(filename);
return true;
}
catch (Exception)
{
return false;
}
}
public static void Main(string[] args)
{
string name, age;
Console.WriteLine(TryReadFile("name.txt", out name) ? name : "An error occured when retrieving the name!");
Console.WriteLine(TryReadFile("age.txt", out age) ? age: "An error occured when retrieving the age!");
}
}
The downside to this approach is that you can't act upon a specific exception, but in the case of simply determining if an operation has or has not succeeded, I find this to be a syntactically clean approach.
I am attempting to create an aspect to manage security on a few properties of a class. However, the security aspect for one member relies on the data in another property of the class. I've read some tutorials on the IntroduceAspect, but I'm not sure it's what I need.
public class ClassWithThingsIWantToSecure
{
[SecurityAspectHere(inherits from LocationInterceptionAspect)]
public int ThingIWantToSecure;
public string ThingINeedToKnowAboutInSecurityAspect;
}
Can someone point me in the right direction for making the runtime value of ThingINeedToKnowAboutInSecurityAspect available in the SecurityAspect?
I have done something a bit like this before, I've knocked up a test on a machine with postsharp installed and just tried it out, here is the code...
class Program
{
static void Main(string[] args)
{
Baldrick baldrick = new Baldrick();
baldrick.ThingINeedToKnowAboutInSecurityAspect = "Bob";
Console.WriteLine("There are {0} beans", baldrick.ThingIWantToSecure);
baldrick.ThingINeedToKnowAboutInSecurityAspect = "Kate";
try
{
//This should fail
Console.WriteLine("There are {0} beans", baldrick.ThingIWantToSecure);
}
catch (Exception ex)
{
//Expect the message from my invalid operation exception to be written out (Use your own exception if you prefer)
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
[Serializable]
public class SecurityAspect : LocationInterceptionAspect
{
public override void OnGetValue(LocationInterceptionArgs args)
{
ISecurityProvider securityProvider = args.Instance as ISecurityProvider;
if (securityProvider != null && securityProvider.ThingINeedToKnowAboutInSecurityAspect != "Bob")
throw new InvalidOperationException("Access denied (or a better message would be nice!)");
base.OnGetValue(args);
}
}
public interface ISecurityProvider
{
string ThingINeedToKnowAboutInSecurityAspect { get; }
}
public class Baldrick : ISecurityProvider
{
public string ThingINeedToKnowAboutInSecurityAspect { get; set; }
[SecurityAspect]
public int ThingIWantToSecure{get { return 3; }}
}
So, the idea here is to interrogate the args.Instance property for the instace of the object that is being decorated.
I have a particular situation where I need to trap exceptions and return an object to the client in place of the exception. I cannot put the exception handling logic at a higher level i.e. wrap Foo within a try clause.
It's best to demonstrate with some sample code. The exception handling logic is clouding the intention of the method and if I have, many methods of similar intent, in the Foo class, I find myself repeating most of the catch logic.
What would be the best technique to wrap the common exception functionality in the code below?
public class Foo
{
public Bar SomeMethodThatCanThrowExcepetion()
{
try
{
return new Bar().Execute();
}
catch(BazException ex)
{
WriteLogMessage(ex, Bar.ErrorCode);
return new Bar() { ErrorMessage = ex.Message, ErrorCode = Bar.ErrorCode;}
}
}
public Baz SomeMethodThatCanThrowExcepetion(SomeObject stuff)
{
try
{
return new Baz(stuff).Execute();
}
catch(BazException ex)
{
WriteLogMessage(ex, Baz.ErrorCode);
return new Baz() { ErrorMessage = ex.Message, ErrorCode = Baz.ErrorCode;}
}
}
}
Updated per Lee's comment
One possibility is to use a generic helper method. Something like this:
T TryExecute<T>(Func<T> action, int ErrorCode)
{
try
{
return action();
}
catch (Exception ex)
{
result = Activator.CreateInstance<T>();
typeof(T).GetProperty("ErrorMessage").SetValue(result, ex.Message, null);
typeof(T).GetProperty("ErrorCode").SetValue(result, ErrorCode, null);
return result;
}
return result;
}
If you can modify Bar and Baz, then you could improve this by placing a requirement on T:
public interface IError
{
public string ErrorMessage { get; set; }
public int ErrorCode { get; set; }
}
T TryExecute<T>(Func<T> action, int ErrorCode) where T : IError
{
try
{
return action();
}
catch (Exception ex)
{
result = Activator.CreateInstance<T>();
result.ErrorMessage = ex.Message;
result.ErrorCode = ErrorCode;
return result;
}
}
Then you'd use:
return TryExecute<Bar>(new Bar().Execute, Bar.ErrorCode);
And:
return TryExecute<Baz>(new Baz(stuff).Execute, Baz.ErrorCode);
That may or may not be an over-abstraction for your particular design; the devil is in the details.
How about a base class:
public class ErrorCapable {
public string ErrorMessage { set; get; }
public int ErrorCode { set; get; }
public static ErrorCapable<T> Oops(Exception exc) where T : ErrorCapable, new() {
// Code for logging error here
return new T() { ErrorMessage = exc.Message, ErrorCode = exc.ErrorCode };
}
}
public class Bar : ErrorCapable {
//...
}
public class Baz : ErrorCapable {
//...
}
Then in the catch, just use, for example:
return ErrorCapable.Oops<Bar>(ex);
Do you really need the explicit logging in every method? Instead of having the exception logic in every method, have one handler in your Main method of the program and handle the exceptions generically.
Also, you don't need to return an arbitrary object from a catch block should you really need the logging there, simply use throw; to let it wander up the stack.
I think the best you can do is something like:
public T TryOrDefault<T>(Func<T> act, int errorCode, Func<BazException, T> onError)
{
try
{
return act;
}
catch(BazException ex)
{
WriteLogMessage(ex, errorCode);
return onError(ex);
}
}
then you can write your other methods in terms of it:
public Bar SomeMethodThatCanThrowException()
{
Bar b = new Bar();
return ExecOrDefault(() => b.Execute(), Bar.ErrorCode, ex => new Bar { ErrorMessage = ex.Message, ErrorCode = Bar.ErrorCode });
}
So I'm working with PostSharp to pull out boilerplate logging/exception handling code so that this:
public void doSomething()
{
Logger.Write("Entered doSomething");
try
{
// code
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, "Errors");
}
Logger.Write("Exited doSomething");
}
becomes this:
[Log]
[HandleExceptions]
public void doSomething()
{
// code
}
but, in certain places I have code that has an instance where known recovery points exist, so it looks like:
public void doSomethig()
{
try
{
// code
}
catch (KnownException ex)
{
ExceptionPolicy.HandleException(ex, "Known");
}
finally
{
this.Recover();
}
}
I'd like to represent this as an advice but I can't seem to get access to members of the class from the advice.
Yes. To invoke a member of the target class from an aspect, you have to import this member into the aspect. See http://doc.sharpcrafters.com/postsharp/2.0/Content.aspx/PostSharp.chm/html/e2086a16-ba9e-43b6-b322-12021b6f24c8.htm.