如何处理空引用和超出范围的异常 [英] how to handle null reference and out of bound exceptions

查看:125
本文介绍了如何处理空引用和超出范围的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
        }
    }

}

推荐答案

它们是不同类型的错误,但类似于它们都告诉您正在尝试引用对象 >不存在



NullReferenceException [ ^ ]



此异常表示正在使用或操作的对象不存在。可能的候选者是类型不匹配(对象引用未设置为对象的实例),有时当您声明变量但忘记使用有效值初始化它时。它可以使用try catch块来处理,但处理它的好方法是初始化变量并确保它们不是 null ;他们确实存在于记忆中



我的博客文章关于 null 例外:代码执行中的空错误 [ ^ ]



IndexOutOfBoundsException



.NET中不存在框架,它是一个基于Java的例外。在.NET框架中有一个 IndexOutOfRangeException [ ^ ]。这意味着您正在尝试引用数组(或集合)限制中不存在的对象。



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).

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





可以通过使用 try catch 来最小化,但处理它的好方法是确保不要在边界外引用一个对象。始终检查集合中对象的计数,然后分别执行。





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.

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





让框架始终处理异常永远不是好方法,你需要知道你在做什么。虽然try catch是忽略意外应用程序破坏的好方法,但它不是开发软件的好方法。您需要自己处理问题,或至少知道将在何处引发异常以处理方案。 if ... else 是一个不错的候选人。



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.


您应该处理问题而不是捕获错误。



例如:

You should handle the issue rather than catching the error.

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

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

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





我永远不会使用try / catch来处理null引用或indexoutofrange错误!



此外,您不应该在Web服务中抛出(或允许抛出)异常,因为它们在调用方法中很难处理。只有在Web服务丢失或关闭时才应抛出Web服务异常。



返回一个简单的错误代码。我使用带响应代码的基本响应对象(成功为00)和错误消息。



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.


这篇关于如何处理空引用和超出范围的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆