Hey everybody I am just getting into C# and was going over exception handling. I am trying to find a way to trigger my custom exception without actually throwing it. It seems clunky to write throw new "custom exception" every time I want to error handle. With the throw line commented out my exception never gets triggered and I know that is because I am originally setting the object to null but can't find a way around this.
public class Person
{
public Person(String name)
{
Name = name;
}
public String Name { get; set; }
}
public class PersonException : Exception
{
public PersonException() : base() {}
}
public class Program
{
static void Main(string[] args)
{
Person p = null;
try
{
p = new Person("kim");
//throw new PersonException();
}
catch (PersonException z) when(p.Name == "kim")
{
Console.WriteLine(z.Message);
}
}
}
}
I don't think you fully understand the concept of exceptions (or your description does not make sense).
Your code will only ever enter the later part of the code below once an exception has occurred. You are not throwing an exception and likewise your code will not result in an exception. Seeing as no exception is occurring and you aren't manually throwing an exception I see no reason why it should ever enter the catch statement. The whole idea is to catch the error, which occasionally you might have to throw.
try {
// your code here
}
catch (Exception ex) {
// here we catch a generic exception
}
...even this wouldn't activate your catch clause because attempting to cast an invalid string to an int would throw an error different to your custom PersonException.
public class Person
{
public Person(String name)
{
Name = name;
}
public String Name { get; set; }
public int Age { get; set; }
}
try
{
p = new Person("kim");
p.Age = Convert.ToInt32("NOT AN INT");
}
catch (PersonException z) when(p.Name == "kim")
{
Console.WriteLine(z.Message);
}
Exceptions are for exceptional circumstances. You just need an if or switch block to check if the person's name is "kim".
All of the things already said by others apply and are good advice and I won't repeat them, but I think that what you're trying to do is better expressed as:
public class Program
{
static void Main(string[] args)
{
Person p = null;
try
{
p = new Person("kim");
if(p.Name == "kim")
{
throw new PersonException();
}
}
catch (PersonException z)
{
Console.WriteLine(z.Message);
}
}
}
...So you only throw the exception when you have the error situation, rather than only catch it in certain situations.
Related
I would like to create my own custom Exception (for my own practice), I have Man class and i would like to check the name (so its not empty, null and only English chars.
I'm not sure if I'm doing this right,
1.do i need to write the code that handles with the error (if occures) in the Custom Exception class? or in the Man's setter?
2. Where should i use the "throw new Exception" for best practice?
3. any comments\improvements about my code would be welcome.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace prog
{
class Program
{
static void Main(string[] args)
{
try
{
Man p = new Man("Dan");
}
catch (Exception e)
{
throw new NameNotValidException(e.Message);
}
}
}
class Man
{
private string name;
public string Name
{
get { return name; }
set
{
if (name == "" || name == null)
{
throw new NameNotValidException("error");
}
name = value;
}
}
public Man(string name)
{
this.name = name;
}
}
class NameNotValidException : Exception
{
public NameNotValidException()
{
Console.WriteLine("Please Write a valid name!");
}
public NameNotValidException(string message)
: base(message)
{
}
public NameNotValidException(string message, Exception inner)
: base(message, inner)
{
}
}
Thanks!
In this case it is more appropriate to throw ArgumentNullException instead. Which exception you end up using (your own or ArgumentNullException) does not matter and does not change the structure of the code below OR how you should handle an Exception.
You want to check value, not name in the setter.
Handle the exception at the calling code. If the calling code is not designed to handle the Exception then do not catch that Exception OR rethrow using throw to preserve the stack trace.
Throw the exception at the location where the code fails due to... (invalid value in this case)
Be careful with your getter/setter code, you were checking the wrong values and also bypassing the setter in the constructor in which case it would never throw an Exception to begin with.
Your Man class.
public class Man {
public Man(string name)
{
// notice capital N for Name so it is set on the property, not the field
// this will execute the setter for the Name property
this.Name = name;
}
public Man(){} // optional, but do not include the parameterized constructor you had as it sets the private fields directly OR include additional validation
private string name;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException("Name cannot be null or empty");
name = value;
}
}
}
Calling code which handles the exception.
try
{
// use parameterized constructor
Man p = new Man("Dan");
// or use an initializer
Man p = new Man{Name = "Dan"};
// the above initializer is actually short for
Man p = new Man();
p.Name = "Dan";
}
catch (ArgumentException e)
{
Console.WriteLine("Error occurred!! Do something...");
}
If you want to create a custom exception just extend any of the exception classes, e.g.:
class MyCustomException : System.Exception
{}
and the you can do throw new MyCustomException();
When you throw an exception you're saying "Hey, something went wrong!", so the caller can then do something about that. The exception's responsibility is to say what exactly went wrong, not how to handle it. So you should remove the Console.WriteLine("Please Write a valid name!"); from the exception. Instead, put that in the code that is actually expecting that error - i.e. your Main method.
static void Main(string[] args)
{
try
{
Man p = new Man("Dan");
}
catch (NameNotValidException e)
{
Console.WriteLine("Please Write a valid name! " + e.Message);
}
Also note that I'm using NameNotValidException in the catch block, not Exception. As a general rule you should be as specific as possible in handling errors - which is why we create custom exceptions in the first place =). For example, let's say you add an Age property, which throws an AgeNotValidException. If you catch Exception e, you'll say "Please Write a valid name!" for every error, including invalid ages. By treating every exception type separately, you can handle each error differently.
About your "throw new Exception" question, you're doing it correctly: You should throw exceptions when you are unable to do something - in this case, you are unable to set the user's name because the given name is invalid. However, you should also try and be more specific with your error messages, to make errors easier to recover from: In your case, you could change it to something along the lines of throw new NameNotValidException("Name can't be empty");, so you can tell the user not only that the name is invalid, but also exactly why.
if you want to change the message only you could use this :
throw new Exception("File check failed!");
As you need to check several types of invalid input (not empty, null and only English chars), my advice is to create the custom exception with a property for invalid input type. The example is below:
class InvalidInputCustomException : Exception
{
public string InputExceptionType { get; set; }
public InvalidInputCustomException(string inputExceptionType)
{
InputExceptionType = inputExceptionType;
}
}
Then you’ll need to create your class Man in which set accessor the input (in this code keyword value) will be checked and code lines - throw new InvalidInputCustomException .. - with corresponding input exception type in this custom exception constructor will be included. This class example is below:
class Man
{
private string _name;
public Man(string name)
{
this.Name = name;
}
public string Name
{
get { return _name; }
set
{
if (value == null)
{
throw new InvalidInputCustomException("null is not valid for input.");
}
else if (value == string.Empty)
{
throw new InvalidInputCustomException("empty is not valid for input.");
}
else
{
foreach (char ch in value)
{
if (!(ch >= 'A' && ch <= 'Z') && !(ch >= 'a' && ch <= 'z') &&
!(ch >= '0' && ch <= '9'))
{
throw new InvalidInputCustomException($"non English character {ch} is " +
$"not valid for input."); ;
}
}
}
_name = value;
}
}
}
The thrown exception must be caught in the place where to initialized Man class object its property Name is attempted to set (as for example:
p.Name = inputString
or through this object constructor as in the code example below).
The example of the Console application code is below:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter name and press key Enter:");
string inputString = Console.ReadLine();
try
{
Man p = new Man(inputString);
Console.WriteLine($"Entered name - {p.Name} - is valid.");
}
catch (InvalidInputCustomException ex)
{
Console.WriteLine($"Invalid input type - {ex.InputExceptionType}. Please enter valid name.");
}
catch (Exception ex)
{
Console.WriteLine("Unhandled exception " + ex.Message);
}
Console.WriteLine("Press any key to finish the program.");
Console.ReadLine();
}
}
The code example is more for custom exceptions understanding purposes. In real applications, you need to avoid exceptions throwing in situations related to user information entering - in this case, data validation tools must be used. During custom exception creation in a real application must be provided at least a parameterless constructor and a best practice is to add three additional constructors: with a string, with a string and an exception, for serialization.
I'm writing a service which's methods must not throw exceptions but should return a generic Message-object which contains the actual result of the method call and exceptions if any have occured. This Message class looks like this:
public class Message<T>
{
private List<Exception> exceptions = new List<Exception>();
public T Result { get; set; }
public void AddException(Exception x)
{
this.exceptions.Add(x);
}
public bool HasExceptions
{
get
{
return this.exceptions.Count > 0;
}
}
public IEnumerable<Exception> Exceptions
{
get
{
foreach (var exception in this.exceptions)
yield return exception;
}
}
}
Usually the implementation of a service method then looks like this:
public Message<int> MyServiceMethod()
{
var msg = new Message<int>();
try
{
// do something useful here
msg.Result = 42;
}
catch (Exception x)
{
msg.AddException(x);
}
return msg;
}
The caller can then handle exceptions if necessary.
var msg = service.MyServiceMethod();
if (msg.HasExceptions)
{
// Handle exceptions here
}
Now I have a service method with an argument which must be in a certain range. Since it feels natural for me to respond with an ArgumentOutOfRangeException if the argument is out of range, I implemented it like this:
public Message<int> MyOtherServiceMethod(int arg)
{
var msg = new Message<int>();
if (arg < 1)
{
msg.AddException(new ArgumentOutOfRangeException("arg", "Argument must be greater than 0"));
return msg;
}
// ...
return msg;
}
Basically this works. The only thing I'm missing is the stack trace of the exception. This is not a problem since I don't need that in my scenario. But it made me wonder, are there any other "side effects" which might cause trouble when the exception is used but not thrown?
You should use some construction that takes message and exception as arguments:
try
{
// do something useful here
}
catch (Exception x)
{
throw YourPreferredException(some_message, x);
}
This will make x available as yourPreferredException.InnerException property.
Also, I don't think it's a good design choice to have a method returning Message and running the try/catch block inside it (should be the other way around).
I would say that's not really the intended use of exceptions in C#. If you want a custom message then you just use the Exception constructor that takes a message and another instance of type Exception, this will give you a new exception with your custom message plus the original exception set as the instances InnerException property. You're just reinventing the wheel here with some custom 'message' class. If all you want to do is return a message (like you don't want to throw) then you should be taking the exceptions Message property and assigning it to some string or returning that string directly.
Here are a couple more idiomatic examples for handling your error;
Message ret = new Message();
try
{}
catch (Exception e)
{
ret.ErrorPropertyOfTypeString = e.Message;
}
return ret;
Message ret = new Message();
try
{}
catch (Exception e)
{
throw new Exception("My custom message here", e);
}
return ret;
Whatever you're doing, one of the two patterns above should probably used instead.
how can i, in my function start to fill the parameters for the class it is supposed to return, but if an exception occurs i'll return my error class instead?
public **** function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return articles;
}
catch (Exception e)
{
Errors Error = new Errors();
Error.exceptionmessage = e.Message;
Error.exceptionname = e.ToString();
Error.httpcode = 500;
return Error;
}
}
is this possible and a good thing to do? or should i just extend all return classes with my error class, even though i will return much info with allot of null values.
i would like to send as little data as possible and if my function fails i'll just send back the error.
UPDATE
sorry for not giving enough inforamtion about my situation this is a function that i want to use in a webservice
[OperationContract]
[WebGet(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
**** Function();
so i dont think i can just throw an exception. i would like to return a class of articles if all is well so i dont have to convert my data to JSON but if something goes wrong i would like to send http code 500 Internal Server Error to the client.
i have not yet read all answers but i think i'll have to include my error class in all my other return classes so the client can now when something went wrong?
UPDATE:
That gives more insight on what you want to do. Since you can't throw exceptions, you should have a base result class. I usually do this for WCF methods I call through javascript, since it can't handle the exceptions nicely.
So you'll want a base class like:
[DataContract]
public class AjaxResult
{
public static AjaxResult GetSuccessResult()
{
return new AjaxResult();
}
[DataMember]
public int Status { get; set; }
[DataMember]
public string Error { get; set; }
}
Then you can inherit this, adding any data you would want to return. This example returns a single product object and a list of validation errors.
[DataContract]
public class SingleProductResult : AjaxResult
{
[DataMember]
public Product Data { get; set; }
[DataMember]
public IList<int> ValidationErrors { get; set; }
}
You can also opt to create a generic wrapper so you don't have to write to much code in your methods. I usually put this in a base class and let all WCF services inherit from that class.
protected T PerformAjaxOperation<T>(Func<T> action) where T : AjaxResult, new()
{
try
{
return action();
}
catch (AccessDeniedException ade)
{
// -- user tried to perform an invalid action
return new T()
{
Status = AjaxErrorCodes.AccessDenied,
Error = ade.ToString()
};
}
catch (Exception ex)
{
return new T()
{
Error = ex.ToString(),
Status = 1
};
}
}
Then just use it like so:
public SingleProductResult GetProduct(int productId)
{
return PerformAjaxOperation(() =>
{
return retval = new SingleProductResult()
{
Data = ProductServiceInstance.GetProduct(productId)
};
});
}
public AjaxResult DeleteProduct(int productId)
{
return PerformAjaxOperation(() => {
ProductServiceInstance.DeleteProduct(productId);
return AjaxResult.GetSuccessResult();
});
}
So, if everything proceeds smoothly, error will be 0 and message will be null. If an exception is thrown, then it will be caught by the PerformAjaxOperation() function and stuffed inside the AjaxResult object (or a derivative of it) and return to the client.
Previous answer:
I don't think this is a good idea. What you can do is create a custom exception by creating a class that inherits from Exception and add properties there that you want to save. Then when an exception occurs, you just catch it and stuff it inside this new exception along with other details. Then throw this exception instead. You can then catch this exception in the higher levels and display the proper message.
an example:
public IList<Articles> GetArticles()
{
try
{
return GetSomeArticlesFromDatabase();
}
catch (Exception innerException)
{
throw new MyCustomException("some data", 500, innerException);
}
}
public class MyCustomException : Exception
{
public int HttpCode { get; set; }
public MyCustomException(string errorMessage, int httpCode, Exception innerException)
: base(errorMessage, innerException) {
HttpCode = httpCode;
}
}
public void EntryPoint()
{
try
{
DoSomething();
var result = GetArticles();
DoSomething();
DisplayResult(result);
}
catch (MyCustomException ex)
{
ReturnHttpError(ex.Message, ex.HttpCode);
}
}
I would honestly advise against doing what you suggest. Instead, either use an existing Exception type or create a new subclass of Exception and throw it. You can even retain the causing exception information in the new exception's InnerException if so desired.
If the situation does not warrant an exception, however (you have not given enough details about what you are doing), you can create a Result class that contains error/warning information. This kind of thing would be better suited for warnings, though. That is, it is not an error condition that prevents things from continuing (exception), but instead a message that the calling code could choose to ignore without drastic side-effects.
For example:
class Result<T>
{
public Result(T Value, Errors Errors = null)
{
this.Value = Value;
this.Errors = Errors;
}
public T Value {get; private set;}
public Errors Errors {get; private set;}
}
Usage (as per your example code):
public Result<Articles> function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return new Result(articles);
}
catch (Exception e)
{
Errors Error = new Errors();
Error.exceptionmessage = e.Message;
Error.exceptionname = e.ToString();
Error.httpcode = 500;
return new Result<Articles>(null, Error);
}
}
If class1 and class2 have a common base type or common interface, use that. But in this case, you could create a wrapper class to encapsulate both result types, like this:
class MethodResult<T>
{
public T Result { get; private set; }
public Errors Errors { get; private set; }
public MethodResult(T result) { this.Result = result; }
public MethodResult(Errors errors) { this.Errors = errors; }
}
public MethodResult<Articles> MyMethod()
{
try
{
...
return new MethodResult<Articles>(articles);
}
catch(Exception e)
{
...
return new MethodResult<Articles>(errors);
}
}
In light of additional information in the question, since this is a WCF service, you could throw a WebFaultException:
public Articles function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return articles;
}
catch (Exception e)
{
throw new WebFaultException(System.Net.HttpStatusCode.InternalServerError)
{
Message = e.Message
};
}
}
The ways that other answers have handled this involve technical methods of how to define the two classes, using interfaces and subclassing.
However, fundamentally you're actually solving the wrong problem. You will still need to write code in the caller that distinguishes between the two types of object, as well as documenting the way in which your function works.
Personally, I would create a new Exception class for the type of error you may be handling, and throw that instead, for example:
public class InvalidArticleException: Exception {
public string ExceptionMessage { get; set; }
public string ExceptionName { get; set; }
public int HttpCode { get; set; }
}
public **** function()
{
try
{
// DO STUFF
return articles;
}
catch (InvalidArgumentException e)
{
throw new InvalidArticleException() {
ExceptionMessage = e.Message,
ExceptionName = e.ToString(),
HttpCode = 500
}
}
catch (Exception ex) { // Not actually required; left in for future debugging
throw ex;
}
}
Callers would then be able to catch the exception and examine it for the error details, with code that is kept separated from that which processes the returned articles.
You can try out keyword,
public Articles function(out Error err)
{
Articles articles = null;
err = null;
try
{
articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
// Set your article values
}
catch (Exception e)
{
Errors ex = new Errors();
ex.exceptionmessage = e.Message;
ex.exceptionname = e.ToString();
ex.httpcode = 500;
err = ex;
}
return articles;
}
I'm not sure why would you want swallowing the exeptions, but if you do whatn this behgaviour make a return type common for both type. The both classes inherit from object so you can change the method signature to public object function()
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
}
Is there a way, how to get currently thrown exception (if exists)?
I would like reduce amount of code and apply some reuse for task looks like:
Exception thrownException = null;
try {
// some code with 3rd party classes, which can throw unexpected exceptions
}
catch( Exception exc ) {
thrownException = exc;
LogException( exc );
}
finally {
if ( null == thrownException ) {
// some code
}
else {
// some code
}
}
and replace it with this code:
using( ExceptionHelper.LogException() ) {
// some code with 3rd party classes, which can throw unexpected exceptions
}
using( new ExceptionHelper { ExceptionAction = ()=> /*some cleaning code*/ } ) {
// some code with 3rd party classes, which can throw unexpected exceptions
}
public class ExceptiohHelper : IDisposable {
public static ExceptionHelper LogException() {
return new ExceptionHelper();
}
public Action SuccessfulAction {get; set;}
public Action ExceptionAction {get; set;}
public void Dispose() {
Action action;
Exception thrownException = TheMethodIDontKnow();
if ( null != thrownException ) {
LogException( thrownException );
action = this.ExceptionAction;
}
else {
action = this.SuccessfulAction;
}
if ( null != action ) {
action();
}
}
}
Is this scenario posible?
Thanks
The idea is that you handle exceptions in the catch block...
That said, Exception is a reference type, so you can always declare an Exception variable outside the try scope...
Exception dontDoThis;
try
{
foo.DoSomething();
}
catch(Exception e)
{
dontDoThis = e;
}
finally
{
// use dontDoThis...
}
What do you think about the following. Instead of looking at the problem as "How to get the last exception?", what if you change it to, "How do I run some piece of code with some more control?"
For example:
Instead of an ExceptionHelper you could have an ActionRunner.
public class ActionRunner
{
public Action AttemptAction { get; set; }
public Action SuccessfulAction { get; set; }
public Action ExceptionAction { get; set; }
public void RunAction()
{
try
{
AttemptAction();
SuccessfulAction();
}
catch (Exception ex)
{
LogException(ex);
ExceptionAction();
}
}
private void LogException(Exception thrownException) { /* log here... */ }
}
It would at least give you some reuse of the SuccessfulAction and ExceptionAction assuming only the AttemptAction varies between calls.
var actionRunner = new ActionRunner
{
AttemptAction = () =>
{
Console.WriteLine("Going to throw...");
throw new Exception("Just throwing");
},
ExceptionAction = () => Console.WriteLine("ExceptionAction"),
SuccessfulAction = () => Console.WriteLine("SuccessfulAction"),
};
actionRunner.RunAction();
actionRunner.AttemptAction = () => Console.WriteLine("Running some other code...");
actionRunner.RunAction();
If you are looking to catch unexpected exceptions you should be handling the UnhandledException. You should only catch exceptions at lower levels that you intend handle (not just to log), otherwise you should let them bubble up and be caught at a higher level, or as I mentioned before in the UnhandledException method.