Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace GridExample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        
        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }


        public List<register> GetDetails(string id)
        {
             List<register> lstrs = new List<register>();
             try
             {


                 SqlConnection con = new SqlConnection("Data Source=2X12Soft;Initial Catalog=test;User ID=sa;Password=bharat");
                 con.Open();
                 SqlCommand cmd = new SqlCommand("select * from depttable", con);

                 SqlDataReader reader = cmd.ExecuteReader();

                 while (reader.Read())
                 {
                     register rs = new register();
                     rs.id = reader["deptid"].ToString();

                     rs.name = reader["deptdame"].ToString();

                     lstrs.Add(rs);
                 }

                 con.Close();

             }
             catch (NullReferenceException ex)
             {

                 nullreference nre = new nullreference();
                 nre.Error = ex.Message;
                 nre.Details = "null reference";
                 throw new FaultException<nullreference>(nre);
             }
             catch (Exception ex)
             {
                 nullreference nre = new nullreference();
                 nre.Error = ex.Message;
                 nre.Details = "null reference";
                 ThrowsTypedCLRFaultException();
                 
             }
            return lstrs;
            
        }
       

        public string ThrowsTypedCLRFaultException()
        {
            throw new FaultException("Error while dividing number");
            //throw new Exception("ThrowsCLRException: IndexOutOfRangeException");//here i am getting the error. how to throw  this type of exception.this is a wcf service and host is windows form
        }
    }

}
Posted
Updated 8-Jun-15 1:22am
v2

They are different kind of errors, but resemble in a way that they both tell you that you are trying to reference an object that doesn't exist.

NullReferenceException[^]

This exception means that the object being used or operated on, doesn't exist. Possible candidates are type-mismatch (Object reference not set to an instance of object) and sometimes when you declare a variable but forget to initialize it with a valid value. It can be handled using the try catch block, but good way to handle it is to initialize the variables and to make sure that they are not null; that they do exist in the memory.

My blog post about null exceptions: What is a null error in code Execution[^]

IndexOutOfBoundsException

Doesn't exist in .NET framework, it is a Java based exception. In .NET framework there is a IndexOutOfRangeException[^]. Which means that you are trying to reference an object that doesn't exist in the limit of the array (or collection).

C#
int[] arr = { 1, 2, 3, 4, 5 }; // Length = 5
Console.WriteLine(arr[10]); // Exception raised


It can be minimize by using the try catch, but the good way to handle it is to make sure that you do not reference an object out side the bounds. Always check the count of the objects in the collection and then perform respectively.

C#
int[] arr = { 1, 2, 3, 4, 5 }; // Length = 5;
if(arr.Length == 5) {
   Console.WriteLine(arr[4]); // index 4 == element 5
}


It is never good way to let the framework always handle the exceptions, you need to know what you are doing. Although try catch is a good way to ignore unexpected application breakage, but it is not a good way to develop the software. You need to handle the problems yourself or at least know where exceptions are going to be raised to handle the scenarios. if...else is a good candidate.
 
Share this answer
 
v2
Comments
Andy Lanng 8-Jun-15 7:13am    
very complete, but neither of us mentioned why you can't (or shouldn't) throw exceptions from a webservice. I will update my solution.
ps: 5* :D
Afzaal Ahmad Zeeshan 8-Jun-15 7:20am    
Actually you can throw the exceptions, from any program. But, that was not the option here. The actual thing was to not catch the exception, but to handle the scenario. :) You can of course throw the exception using throw new Exception("Error");. But, the concern was how to handle the error. Handling the error means, finding another way of proceeding the program execution.

Thank you for your vote.
Andy Lanng 8-Jun-15 7:22am    
I agree. And you "can" throw an exception from the webservice but my point was that you get the dirty yellow html page back in your response. No one want to parse that :S
Or is that only ASP? I could be talking out of my arse if it's different in other project types
Afzaal Ahmad Zeeshan 8-Jun-15 7:24am    
Yellow page of death is ASP.NET based, not a Web Service (WCF) based. To handle that error also, ASP.NET allows you to have custom error pages. But still, you need to find a way around to handle the scenario. :)
Andy Lanng 8-Jun-15 8:10am    
Ah k. I am talk from behind ^_^

Well now I know :D
You should handle the issue rather than catching the error.

for example:
C#
if(myvar==null)
  return "error_01";

string[] myvars = myvar.split(',')

if(myvars.length==0)
  return "error_02";


I would never use try/catch to handle null reference or indexoutofrange errors!

Also, you shouldn't throw (or allow to be thrown) exceptions in a webservice because they are so difficult to handle in the calling method. Web Service exceptions should only be thrown if the webservice is missing or down.

Return a simple error code instead. I use a base response object with a response code ("00" for success) and the error message.
 
Share this answer
 
v3
Comments
Afzaal Ahmad Zeeshan 8-Jun-15 7:07am    
Good answer, see my Solution 2 for more on this topic. I have provided more details on this for the OP.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900