return value in Try Catch with generics - c#

I'm having a problem specifying the proper return value in a try/catch block.
I'm novice level scripter and have never used generics before.
The error message is:
"An object of type convertible to T is required"
What specifically do I need to return at the end of my try/catch?
private static T LoadData<T>(string filePath)
{
try
{
return JsonUtility.FromJson<T>(File.ReadAllText(filePath));
}
catch(Exception e)
{
// Something went wrong, so lets get information about it.
Debug.Log(e.ToString());
return ?????;
}
}

It really depends on the application behaviour that you want to define. You can have it return a new T() / default (I wouldn't advise this as users cant tell if the operation was successful or not) or you can throw the exception up a level so that it can be handled else where. The whole point of a try catch is to handle unexpected specific behaviour, thus its not a good idea to catch generic exceptions unless you have a generic way of handling it.

When something went wrong we can't just ignore it; if we don't have enough information to make a decision, a best option is to escalate the problem: may be a top level method knows what to do.
So I suggest to rethrow the exception instead of returning any value:
private static T LoadData<T>(string filePath)
{
try
{
return JsonUtility.FromJson<T>(File.ReadAllText(filePath));
}
catch(Exception e)
{
// Something went wrong, so lets get information about it.
Debug.Log(e.ToString());
// let top level method decide what to do:
// 1. Do nothing (just ignore the exception)
// 2. Do something (e.g. change permission) with filePath
// 3. Try load from some other file
// 4. Try load from some other source, say RDBMS
// 5. Use some default value
// 6. Close the application
// 7. ....
throw;
}
}
Please note, that here, within LoadData<T> method we don't know the context, and that's why we can't decide which option from 1..7 is the best one

Related

Right way of handling errors and keep going

We have a requirement of parsing/validating a large number of rows read from CSV or Excel files. We read the row and apply business rules to check if all the cells/columns contain the valid data.
The application should keep validating records/columns till end even if some error occurs at an error or column. Currently we are going like this:
private void ValidateRow(RowObject obj)
{
try
{
foreach(var col in obj.Cells)
{
ValidateColumn(col);
}
}
catch(Exception ex)
{
//LOG ERROR
}
}
The columns are validates like this:
public void ValidateColumn(ColumnObject c)
{
try
{
//validate c
}
catch(Exception e)
{
//LOG Column Error
}
}
We are handling error at two places when validating rows (ValidateRow) and then for each column (ValidateColumn). My question is whether this is valid or optimal way of handling error or something more optimal be done?
Since we don't know your Business logic it's difficult to tell. But I would recommend to evaluate all possible exceptions and handle them in different catch blocks. This enables you to handle errors more specific. A good hint is to use Microsofts StyleCop and FxCop. They help you to write good code. In this case they would tell you to not catch general Exceptions.
I think your way is very correct and optimal. If you want to keep going, you should always have a try/catch inside the foreach. But I guess you don't really need the outer try/catch in this case as it will only fail if obj or obj.Cells is null. Unless you have posted only part of your code. Though I agree with comments that validation should not throw exception in the first place but if you are using some 3d party library or any complex code that you are not sure of, it's better to handle it the way you did.

In MVC what is the best method to manage exceptions or errors in the business?

In MVC what is the best method to manage exceptions or errors in the business? I found several solutions but do not know which to choose.
Solution 1
public Person GetPersonById(string id)
{
MyProject.Model.Person person = null;
try
{
person = _personDataProvider.GetPersonById(id);
}
catch
{
// I use a try / catch to handle the exception and I return a null value
// I don't like this solution but the idea is to handle excpetion in
// business to always return valid object to my MVC.
person = null;
}
return person;
}
Solution 2
public Person GetPersonById(string id)
{
MyProject.Model.Person person = null;
person = _personDataProvider.GetPersonById(id);
// I do nothing. It to my MVC to handle exceptions
return person;
}
Solution 3
public Person GetPersonById(string id, ref MyProject.Technical.Errors errors)
{
MyProject.Model.Person person = null;
try
{
person = _personDataProvider.GetPersonById(id);
}
catch (Exception ex)
{
// I use a try / catch to handle the exception but I return a
// collection of errors (or status). this solution allow me to return
// several exception in case of form validation.
person = null;
errors.Add(ex);
}
return person;
}
Solution 4
// A better idea ?
I would also suggest you to think about Null Object Pattern. Instead of returning null, return an empty object so that you don't have to perform multiple if null checks. You should create an abstract Person class that has a static property like NullPerson which contains default values. If your DAL returns null, you would return NullPerson. You can find more information on Null Object Pattern.
Let the exceptions be handled at the application level. I would suggest to go with Solution 2. You could use try..catch blocks when you want to change the logic when some exception happens else simply leave it to the application infrastructure.
System errors should be caught as soon as possible, while each and every object consuming your class should implemented necessary code to catch possible errors. Catching system errors at the lowest level lets you decide what you plan to do:
- Return no value
- Throw a custom error
- Rethrow the system error
Inserting an abstraction layer between system error and your custom error is that you can introduce new error requiring different attention. I.E.: if the error is FileNotFoundException, you might want make a difference between a normal error (i.e.: the file is a daily report but the file asket represent a future report) or not (the file should exist)
I would prefer solution 3, even if in a first phase you simply rethrow a regular exception when needed.
Serge
That depends upon your requirement.
IF you just want to know whether our process successfully executed or not then Process 2 is advisable.
IF you are willing to write some error logs then Process 3 is best choice.
If you don't want to go with complex method yet you want to handle exception and write logs of it, then Process 1 is advisable.
Regards,
Pavan.G

C# Catch Exception

Which exception would I use in a try/catch to find out when the user has inputted data in the wrong format?
Example:
try
{
string s = textBox1.Text;
// User inputs an int
// Input error
MessageBox.Show(s);
}
catch(what exception)
{
MessageBox.Show("Input in wrong format");
}
Thanks
Don't do this. It's a misuse of exception handling. What you are attempting to do is considered coding by exception, which is an anti-pattern.
An exception is exactly what it sounds like, an exception to the norm. It's defined by something you either haven't accounted for, or simply can't account for through traditional validation. In this situation, you can definitely account for a format issue ahead of time. If you know there is a possiblity that the inputted data will be in the wrong format, check for this case first. e.g.
if(!ValidateText(textBox1.text)) // Fake validation method, you'd create.
{
// The input is wrong.
}
else
{
// Normally process.
}
You should avoid using Exceptions as flow control.
If you want a textbox to be an int, this is where int.TryParse() method comes in handy
int userInt;
if(!TryParse(textBox1.Text, out userInt)
{
MessageBox.Show("Input in wrong format");
}
You can go with Exception ex to catch all exceptions. If you want to catch a more specific one, though, you'll need to look at the documentation for whatever functions you are using to check the validity of the input. For example, of you use int.TryParse(), then you will want to catch FormatException among others (see: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx for more information).
You can create your own exception like ↓
public class FormatException : Exception
And In your source , it might be...
if (not int) throw new FormatException ("this is a int");
Then , In your catch ...
catch(FormatException fex)

High Order Function Approach for Exceptions in C#

Hey everyone, I was thinking about passing method blocks around as arguments to helper classes that built in exception handling but it's one of those things that is intuitive and I'd like to submit it for criticism, insight, or advice.
I would like to note up front that this is NOT how I do all of my exception handling, but there are cases where I find this structure more "readable."
For example, I have a scenario where I'm showing a preview image but if that fails (this is a real scenario where I'm previewing images and certain GIF/BMP formats cannot be previewed) it's simply a scenario where I display an alternate image instead of preview. The try/catch code block that looks like this:
try
{
alternatePreviewImage.SetSource(fs);
}
catch (Exception ex) {
requiresSpecialPreview = false;
previewImage = new BitmapImage(new Uri("Images/NoPreviewAvailable.png", UriKind.Relative));
}
So I'll leverage a helper class that takes a method parameter to make it look like this:
if(!ErrorHelper.RunWithSuccessNotify(()=> alternatePreviewImage.SetSource(fs))){
requiresSpecialPreview = false;
previewImage = new BitmapImage(new Uri("Images/NoPreviewAvailable.png", UriKind.Relative));
}
The ErrorHelper.RunWithSuccessNotify is quite simple:
public static bool RunWithSuccessNotify(Action code) {
bool success = true;
try
{
code();
}
catch (Exception ex)
{
success = false;
}
return success;
}
Let me again underscore that it is useful for these low impact scenarios, as well as others where I may be able to suppress the exception:
public static void RunWithErrorSuppression(Action code) {
try
{
code();
}
catch (Exception ex)
{
// pass
}
}
The approach could be more detailed too, to allow for capturing the exception:
public static void ExecuteWithLogging(Action code, Action<Exception> handles) {
try
{
code();
}
catch (Exception ex)
{
handles(ex);
}
}
So what are thoughts on this set of tactics to centralize exception handling? If it is a bad direction, are there specific reasons why it might end up getting me in trouble?
The main problem I would have with this approach is catching Exception is generally considered bad form. If there was some way to specify which type of exception to catch I might buy it, but I believe that has to be specified at compile time. I also wouldn't feel completely comfortable with catching all exceptions and rethrowing the ones that don't match.
Remember, when you catch an exception, you're essentially saying that you can handle the error in some meaningful way. Obviously, the code above can't handle StackOverflowException or MissingMethodException.
Don't trap all the exception, parametrize the one you want:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProvaException
{
class Program
{
static void Main(string[] args)
{
int a = doWithException<int>(divide, 0, typeof(DivideByZeroException), x => 300);
Console.WriteLine(a);
Console.ReadKey();
}
public static int divide(int b)
{
return 10 / b;
}
public static T doWithException<T>(Func<T, T> a, T param1, Type exType, Func<Exception, T> handFunction) {
try
{
return a(param1);
}
catch(Exception ex) {
if(exType.Equals(ex.GetType())) {
return handFunction(ex);
}
else
throw ex;
}
}
}
}
Not very C# like, but it can be useful in same case (when you want to abstract handling exception).
You have to write a different type signature for every type of function, because C# doesn't support currying. Veeeeeeeeery boring. :D
It's not a very elegant solution, but it gives you an hint on how things works in functional languages. It's very fun to learn.
Hello i don't know if it scale well but for now my team is using it in our measurement software to handle special exception (like communication with some measurement device lost) and restart the measurement in this case.
For now it's working well especially in cases where the important / non repetitive part of the code is in the function (Action parameter) being called and not really in the exception handling.
The best case being that they even could be nested and the main code kept readable.
On the other side you are hiding what exactly your exception handling is doing behind a function name, so it should be simple or clear enough to be understandable just by the name of the function, otherwise you are obfuscating something from the future readers of your code (yourself included)
My initial thought is simply that passing complex anonymous delegates around smells bad. There's nothing stopping someone from dumping an anonymous delegate with complex logic into the ErrorHelper methods. Such logic then becomes difficult to test. I would prefer logic to be passed only in an object, which to me seems to be a better understood technique. To me anonymous delegates (and lambdas) are for very simple logic extensibility, like comparison logic. The mechanics of anonymous delegates are powerful and can be used for other things, but with great power comes great responsibility. =)
What you achieve with your technique is the ability to cleanly change the exception handling strategy at runtime. But is this an actual requirement?
Have a look at THIS and maybe whip out the ol' Reflector on it for a bit. Seems to me like the same things are done there but possibly in a more complete way... It seems very powerful...
If I've understood what you're trying to do, then it feels horrible to me as a standard error management pattern. That's a warning sign right there, as it took me a while to grasp your idea.
Unless there's a good reason, code should be explicitly available in the method for any maintenance developer to view and modify, not passed around from other locations. Just because a feature exists doesn't mean that it's useful in most situations. In this case, I can't see any benefit from the obfuscation.
BTW, I think you're nailing the corpse to the wall by catching System.Exception. The normal rule is not to catch an exception unless you know what the exception is and/or you need to know the exception detail for some reason.
A commonly-used pattern for recovery in the event of an unknown exception looks something like this:
bool exceptionHappened = true;
try
{
alternatePreviewImage.SetSource(fs);
exceptionHappened = false;
}
finally
{
if ( exceptionHappened )
{
requiresSpecialPreview = false;
etc;
}
}

C# what kind of exception should I raise?

I am currently in a try catch finding if a property has been set properly to the bool value that it should be like this...
public void RunBusinessRule(MyCustomType customType)
{
try
{
if (customType.CustomBoolProperty == true)
{
DoSomething();
}
else
{
throw new Exception("This is obviously false or possibly null lets throw up an error.");
}
}
catch(Exception)
{
throw;
}
}
Now the deal with throwing this error for me is that I am using Microsoft's source analysis and it gives me an error stating "CA2201 : Microsoft.Usage : Object.RunBusinessRule(MyCustomType)creates an exception of type 'Exception', an exception type that is not sufficiently specific and should never be raised by user code. If this exception instance might be thrown, use a different exception type.
Soooo What exception should I throw that would be specific enough for Microsoft.., for the circumstance of throwing an error about my own application's logic handling and when I want to "throw".
ArgumentException
InvalidOperationException
FormatException
The passed in argument wasn't good.
Create your own exception extending Exception. E.g.: RuleViolationException
Should you be throwing an exception at all?
Having a false boolean value isn't exactly an exceptional circumstance.
EDIT
My original answer was a bit terse so I'll elaborate...
From your example it's not clear what the actual objects, properties and methods represent. Without this information, it's difficult to say what type of exception, if any, is appropriate.
eg, I'd consider the following a perfectly valid use of an exception (and your real code might well look something like this, but we can't tell from your example):
public void UpdateMyCustomType(MyCustomType customType)
{
if (!customType.IsUpdateable)
throw new InvalidOperationException("Object is not updateable.");
// customType is updateable, so let's update it
}
But in the general case, without knowing more about your domain model, I'd say that something like this (a false boolean value) isn't really exceptional.
ArgumentException maybe?
A case could be made for InvalidOperationException, too.
The answer here is that you shouldn't throw any exception. Why throw an exception just to catch it again in a second and rethrow it?
A slight aside, but you could simplify your code somewhat...
public void RunBusinessRule(MyCustomType customType)
{
if (customType.CustomBoolProperty == false)
{
throw new Exception("This is obviously false or possibly null lets throw up an error.");
}
DoSomething();
}
As for the type of exception to throw, you might consider ApplicationException or InvalidOperationException, or you could define your own exception type.
I know that a question is about throwing an exception but I think it would be more appropriate to do an assertation here:
// Precondition: customType.CustomBoolProperty == true
System.Diagnostics.Debug.Assert(customType.CustomBoolProperty)
DoSomething();
InvalidArgument exception is fine but better yet, an ApplicationException.
The other answers are fine for quick resolution, but ideally if you know at compile time that a certain method should never be invoked using certain parameters, you can prevent that from ever happening by inheriting your custom type, instanciating it only when that custom bool is true, and now your method looks like.
public void RunBusinessRule(MyInheritedType inheritedObject)
{
//No need for checks, this is always the right type.
//As a matter of fact, RunBusinessRule might even belong to MyInheritedType.
}
This is the I in SOLID.
I think you should avoid exceptions for code logic.
I suggest to modify your method to return the result of your method as a bool type then you may decide the appropriate way to show an error message to the user at the time of calling the method:
public bool RunBusinessRule(MyCustomType customType)
{
try
{
if (customType.CustomBoolProperty == true)
{
DoSomething();
return true;
}
return false;
}
catch(Exception)
{
throw;
}
}
Make your own custom exception by extending System.Exception and throw that. You can get even crazier and have a whole tree of exception types if you want.
You could just create a custom ValidationException that is only used for your business logic validation. Or you could create a separate validation exception for each type of validation error although that is probably overload.
Not really what you were asking for, but there are plenty of people who have already given answers that I agree with, but you should also avoid only using catch(Exception ex).
It is a much better practice to try to catch the specific Exceptions that are possible first and if need be, catch the generic Expception. eg:
try{
MyMethod(obj);
}catch (NullReferenceException ne){
//do something
}
catch(UnauthorizedAccessException uae){
//do something else
}
catch(System.IO.IOException ioe){
//do something else
}
catch(Exception){
//do something else
}

Categories