On Error Resume Next in C#

Questpond
Posted by in C# category on for Advance level | Views : 33055 red flag

This is a very simple article and some people may really find it not worth to be termed as article. One of my junior was working for a full day on this. Just wanted to ensure that other people do not face the same problem. In this article we will try to understand how we can simulate the On Error Resume Next feature of VB.NET in C#. We all understand that it’s a bad thing to handle errors, but sometimes some process should continue irrespective there is error or not.
Title:        On Error Resume Next in C#
Author:      Shivprasad Koirala 
Email:       shiv_koirala@yahoo.com
Language:    C#
Level:       Beginner
Description: On Error Resume Next in C#

On Error Resume Next in C#
 

Introduction
 



This is a very simple article and some people may really find it not worth to be termed as article. One of my junior was working for a full day on this. Just wanted to ensure that other people do not face the same problem. In this article we will try to understand how we can simulate the On Error Resume Next feature of VB.NET in C#. We all understand that it’s a bad thing to handle errors, but sometimes some process should continue irrespective there is error or not.
 

I would like really hear from every one if there are better ways of doing this.
 

I have been writing and recording lot of architecture related videos on design patterns, UML, FPA estimation, C# projects etc you can watch my videos on http://www.questpond.com 
 

The Problem
 

In VB.NET we have a very decent feature called as ‘On Error Resume Next’. With this any errors happening on the VB.NET code is by passed and the next statement is taken. This feature is not good as it by passes the whole error handling engine. But many times we would like to bypass errors for various reasons.


For instance we are making a XML parser and in case there is an error while parsing we want to log that error but continue parsing ahead. In these situations by pass error engine and continue execution is much needed. In VB.NET we can achieve this by using ‘On Error’ statement but in C# there is no statement as such.
 

Solution
 

Below is a simple code which explains the same in detail. We have a simple for loop below; in real time project this for loop can be some kind of process which should go on even if there is error. What I have done is moved the code from the main for loop area to a different method and wrapped that method with an empty catch. Now even if there is an error in the method it does not affect my for loop. The for loop will still continue looping through all numbers irrespective of any errors.
 

Page copy protected against web site content infringement by Copyscape

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)