Programing tip: Dealing with annoying exceptions

1    13 Mar 2016 22:20 by u/roznak

As I stated before: "Exceptions are **not** your friend" if you create code that is part of a big and complex project.

But if you are out of luck and have to deal with a project that does use exceptions, then this trick will help to hide these annoying exceptions that hides the functional code. The key to rock stable code is that you can see what the code should do and not what is should not do.

Realize that that catch statement can be way more simplified. Don't let the fact that "throw" is used that exceptions are something magical. They are just normal classes and you can deal with them just like any normal class.

Create a method that accepts the exception as a parameter. ~~~ private void ProcessException(Exception e){ if (e is Exception1) { var ex1= e as Exception1; log.WriteLine(ex1.Message, ex1.SomeProperty1) } if (e is Exception2) { var ex2= e as Exception2; log.WriteLine(ex2.Message, ex2.SomeProperty2) } else { log.WriteLine(e.Message) } ~~~ Now you can use it like this:

~~~ public method1(){ try { // do something } catch (exception e){ ProcessException(e); } }

public method2(){ try { // do something } catch (exception e){ ProcessException(e); } }

public method3(){ try { // do something } catch (exception e){ ProcessException(e); } ~~~

The number of lines in your code that gets occupied can in a lot of cases be reduces dramatically.

You can even go further

~~~ private void ProcessException(string function, Exception e){ if (e is Exception1) { var ex1= e as Exception1; log.WriteLine(function, ex1.Message, ex1.SomeProperty1) } if (e is Exception2) { var ex2= e as Exception2; log.WriteLine(function, ex2.Message, ex2.SomeProperty2) } else { log.WriteLine(function.Message) } ~~~

Your code now also includes more user friendly information.

~~~ public method2(){ try { // do something } catch (exception e){ ProcessException("Class1.method2";e); } } ~~~

And even get rid of the exception handling method and move it to another class

~~~ public method2(){ try { // do something } catch (exception e){ ExceptionHandler.ProcessException("Class1.method2",e); } } ~~~

0 comments

No comments archived.