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.
Related
Is there any reason to use specific expetion classes MyException1 and MyException2 in this case?
public static void Main()
{
try
{
TestMethod();
}
catch(Exception ex)
{
Console.Writeline(ex);
}
}
private static void TestMethod()
{
// This method can throw Exception1 and Exception2
}
public class MyException1 : Exception {}
public class MyException2 : Exception {}
I know that it makes sense in case when we have several catch blocks for each exception type. But in this case MyException1 and MyException2 are similar empty. These throwed exceptions will be casted to Exception class in the Main method. Maybe is it better not to create two similar Exception classes with such handling?
The concept behind a catch block is that you handle the exception. If a certain type of exception requires a certain type of handling, it is helpful when that exception has its own class, so it can have its own catch block.
For example, if MyException1 can be safely swallowed while MyException2 is fatal, you could write:
try
{
DoSomethingHard();
}
catch (MyException1 exception1)
{
_log.Write("Warning: small exception, no worries. {0}", exception1.Message);
continue;
}
catch (MyException2 exception2)
{
_log.Write("Fatal: big exception, gotta bail out now. {0}", exception2.Message);
break;
}
Exceptions should be wide rather than deep. Have a different exception for each, erm... exception.
Your example doesn't really show a good example. Perhaps if it was more like:
public static void Main()
{
try
{
TestMethod();
}
catch(Exception ex)
{
Console.Writeline(ex);
}
}
private static void TestMethod()
{
if(..bad configuration)
throw new ConfigurationException("configuration item");
if(missing file)
throw new FileMissingException("filename");
// This method can throw Exception1 and Exception2
}
public class ConfigurationException : Exception {}
public class FileMissingException : Exception {}
If you are using ASP.NET, its so common that you create and use your own Exception handler, in that case, you can to consider specific behavior for each exception in only one method (not catch block in every error prone code blocks), look at this simple example:
public class MyExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
if (context.Exception is SqlException)
{
//do something...
}
else if (context.Exception is HttpListenerException)
{
//do something...
}
else
{
//do something else...
}
}
}
I'm trying to find a code to exit the whole method if an exception occurs in a sub method. I tried adding return in catch section of Subfunction() but the process will continue to Thirdfunction()
public static void Mainfunction()
{
try
{
//some code
//some code
Subfunction();
ThirdFunction();
}
catch(Exception ex)
{
//write to log
}
}
public static void Subfunction()
{
try
{
//some code
//some code
}
catch (Exception ex)
{
//write to log
}
}
So basically if an error occured in the Subfuntion() I want to stop the process from the Mainfunction() without continuing to the ThirdFunction(). Any help will be highly appreciated. Thanks
if an error occured in the Subfuntion() I want to stop the process
from the Mainfunction()
The simplest way to remove try/catch in your method Subfunction
If you want to keep the try/catch in this method, (for logging or something), rethrown exception
public static void Main()
{
try
{
Subfunction();
Thirdfunction();
}
catch(Exception ex)
{
}
}
public static void Subfunction()
{
try
{
throw new AccessViolationException();
}
catch (Exception ex)
{
throw;
}
}
There are basically two sets of possible solutions: With use of Exceptions and without.
With the use of exceptions, I'd recommend to just let it bubble up , as I've already said in comments.
Then you can rethrow:
try {
// exception here
}
catch(Exception ex)
{
throw;
// Attention: this is _different_ from "throw ex" !!
}
Pay attention here:
You can also use the throw e syntax in a catch block to instantiate a new exception that you pass on to the caller. In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.
See throw (C# Reference) (emphasis by me)
Coming over from Java myself, this is something people like myself will trip over during transitioning from Java to .Net. So if you got "java guys" new on the team: don't be harsh on them, just point them to the docs.
You can wrap:
try {
// exception here
}
catch(Exception inner)
{
throw new MyCustomException( "Some custom message", inner);
}
BTW: It is generally not a good idea to catch Exception. Most of the time you'd want to catch specific exceptions that you can actually handle.
The other class of solutions is without bubbling up exceptions:
Return value:
public static bool Subfunction()
{
bool success = true;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = false;
}
return success;
}
Or with return or error codes:
// DO NOT USE MAGIC NUMBERS !
private static readonly int SUCCESS_INDICATOR = 0;
private static readonly int ERROR_INDICATOR = 1;
// TODO DOCUMENT which errorcodes can be expected and what they mean!
public static int Subfunction()
{
int success = SUCCESS_INDICATOR;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = ERROR_INDICATOR;
}
return success;
}
Especially with "C-Guys" on the team you may stumble across this one. (No offense - just my experience)
Or with a state object ...
public static void Mainfunction()
{
try
{
//some code
//some code
ISuccessIndicator success = new ISIImplementation();
Subfunction( success );
if( !succes.HasException )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThrirdFunction or "else" branch are caught here.
}
}
public static void Subfunction( ISuccessIndicator result )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
result.HasException=true;
result.Exception = ex;
}
}
public interface ISuccessIndicator
{
Exception Exception {get; set;}
bool HasException {get; set;}
}
And if you are really crazy you could ...
public static void Mainfunction()
{
try
{
//some code
//some code
Exception ex = null;
Subfunction( ref ex );
if( ex == null ) // or more modern: ( ex is null )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThirdFunction or "else" branch caught here.
}
}
public static void Subfunction( ref Exception outEx )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
outEx = ex;
}
}
Please mind, that I in no way would encourage using the latter. But it is possible ... and OP asked for possibilities.
Disclaimer: All snippets untested. Who finds errors can keep them (but please write a comment, so I can fix them).
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.
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.
I have tried to implement automatic resource management for Java (something like C#'s using). Following is the code I have come up with:
import java.lang.reflect.*;
import java.io.*;
interface ResourceUser<T> {
void use(T resource);
}
class LoanPattern {
public static <T> void using(T resource, ResourceUser<T> user) {
Method closeMethod = null;
try {
closeMethod = resource.getClass().getMethod("close");
user.use(resource);
}
catch(Exception x) {
x.printStackTrace();
}
finally {
try {
closeMethod.invoke(resource);
}
catch(Exception x) {
x.printStackTrace();
}
}
}
public static void main(String[] args) {
using(new PrintWriter(System.out,true), new ResourceUser<PrintWriter>() {
public void use(PrintWriter writer) {
writer.println("Hello");
}
});
}
}
Please analyze the above code and let me know of any possible flaws and also suggest how I can improve this. Thank you.
(Sorry for my poor English. I am not a native English speaker.)
I would modify your using method like:
public static <T> void using(T resource, ResourceUser<T> user) {
try {
user.use(resource);
} finally {
try {
Method closeMethod = resource.getClass().getMethod("close");
closeMethod.invoke(resource);
} catch (NoSuchMethodException e) {
// not closable
} catch (SecurityException e) {
// not closable
}
}
}
Also, you need to define the behavior you want for the case that the resource is not closable (when you catch the above exceptions). You can either throw a specific exception like UnclosableResourceException or completely ignore this case. You can even implement 2 methods with these 2 behaviors (using and tryUsing).