I have a class with different methods doing the same thing reading a file. I want to use try-catch block for exception handlin开发者_JAVA百科g. I want to ask if there is any way so that all methods will go inside a single try block as every method will give same exception "file not found"..
My preferred way of handling that would be to call a common method from all of them, so each (individually) looks like:
try {
// code
} catch(SomeExceptionType ex) {
DoSomethingAboutThat(ex);
}
However, you can also do it with delegates, i.e.
void Execute(Action action) {
try {
// code
} catch(SomeExceptionType ex) {
// do something
}
}
and
Execute(() => {open file});
You can use this technique to wrap an action using an extension method:
public static class ActionExtensions
{
public static Action WrapWithMyCustomHandling(this Action action)
{
return () =>
{
try
{
action();
}
catch (Exception exception)
{
// do what you need
}
};
}
}
public class DummyClass
{
public void DummyMethod()
{
throw new Exception();
}
}
and then call it as below:
DummyClass dummyClass = new DummyClass();
Action a = () => dummyClass.DummyMethod();
a.WrapWithMyCustomHandling()();
So basically you can wrap any Action with this.
If I understand the question you can't have a single try
catch
block, but you can call a method from the catch
so all methods will share the same exception handling:
try
{
.... your code
}
catch (SomeException e)
{
ExceptionHandler(e);
}
You either have to add the try
-catch
around the contents of each method in your class, or go up one level of scope to where your methods are called and enclose those in try
-catch
s.
There's no way to apply the same exception handling to every method in a class (if there was, I wouldnt reccommend it anyway.)
The fact that you have "a bunch of methods doing the same thing" seems like the source of the problem. Can you make that into one method?
Also, you could wrap the try catch block outside of the methods that are being called. That way the caller can do the exception handling - the methods just need to throw them.
In case you want all those methods to work on a file stream you could create a method that takes an action working on a file stream and the name of the file. In this method catch the relevant exception, in your case FileNotFoundException and return to the caller, not invoking the action. Otherwise invoke the action on the filestream and return to the caller.
Definition:
private bool PerformActionOnFileStream(Action<FileStream> action, string path)
{
try
{
using(FileStream fileStream = new FileStream(@path, FileMode.Open))
{
action(fileStream);
}
}
catch(FileNotFoundException)
{
return false;
}
}
Usage:
private void PrintContentOfFile(string path)
{
Action<FileStream> action = fileStream => PrintContentOfFileStream(fileStream);
bool didPerformAction = PerformActionOnFileStream(action, path);
if(!didPerformAction)
{
// Handle error.
}
}
Aliostad's answer is the closest to what you're actually asking for, and it's a pretty cool solution, but honestly I think this is a matter of refactoring your code. As skaz says, the fact that they're all doing the same thing means they can probably all be consolidated into a single method.
To get the closest to what you're looking for without completely changing the way you do business, I'd suggest a common error handling class within your solution, and a snippet which extends the standard Try-Catch snippet, but still passes enough information to your handler so you can do some specific exception handling and custom error messages.
Your custom error handling class should have a method like the following:
public void HandleError(Sysem.Reflection.MethodBase MethodBase, Exception Exception);
This, or something similar is what I would recommend for your snippet.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>try</Title>
<Shortcut>try</Shortcut>
<Description>Code snippet for try catch</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>expression</ID>
<ToolTip>Exception type</ToolTip>
<Function>SimpleTypeName(global::System.Exception)</Function>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[try
{
$selected$
}
catch (Exception ex)
{
YourErrorHandler.HandleError(System.Reflection.MethodBase.GetCurrentMethod(), ex);
}]]>
</Code>
</Snippet>
</CodeSnippet>
Obviously, you can extend the HandleError method in anyway you see fit - in my snippets, for the web, I pass information about the current user, but you can use anything you'd like.
Best of luck!
Adam
精彩评论