Özel durumlarExceptions

C# ' deki özel durumlar, hem sistem düzeyini hem de uygulama düzeyi hata koşullarını işlemek için yapılandırılmış, Tekdüzen ve tür açısından güvenli bir yol sağlar.Exceptions in C# provide a structured, uniform, and type-safe way of handling both system level and application level error conditions. C# ' deki özel durum mekanizması, birkaç önemli farklılık ile C++ ' ın tam olarak benzerdir:The exception mechanism in C# is quite similar to that of C++, with a few important differences:

  • C# ' de, tüm özel durumların, öğesinden türetilmiş bir sınıf türü örneğiyle temsil etmelidir System.Exception .In C#, all exceptions must be represented by an instance of a class type derived from System.Exception. C++ ' da, herhangi bir türde herhangi bir değer bir özel durumu temsil etmek için kullanılabilir.In C++, any value of any type can be used to represent an exception.
  • C# ' de, bir finally bloğu (TRY deyimleri) hem normal yürütme hem de olağanüstü koşullarda yürütülen sonlandırma kodunu yazmak için kullanılabilir.In C#, a finally block (The try statement) can be used to write termination code that executes in both normal execution and exceptional conditions. Kodu çoğaltmadan C++ ' ta yazmak zordur.Such code is difficult to write in C++ without duplicating code.
  • C# ' de, taşma, sıfıra bölme ve null başvuru gibi sistem düzeyi özel durumlar iyi tanımlanmış özel durum sınıflarına sahiptir ve uygulama düzeyi hata koşulları ile aynı şekilde bulunur.In C#, system-level exceptions such as overflow, divide-by-zero, and null dereferences have well defined exception classes and are on a par with application-level error conditions.

Özel durumların nedenleriCauses of exceptions

Özel durum iki farklı şekilde oluşturulabilir.Exception can be thrown in two different ways.

  • Bir throw ifade (throw deyimleri) hemen ve koşulsuz bir özel durum oluşturur.A throw statement (The throw statement) throws an exception immediately and unconditionally. Denetim, hemen sonrasında ifadeye hiçbir şekilde ulaşmaz throw .Control never reaches the statement immediately following the throw.
  • C# deyimlerinin ve ifadesinin işlenmesi sırasında ortaya çıkan bazı özel durumlar, işlem normal olarak tamamlanamayan bazı durumlarda özel durumlara neden olur.Certain exceptional conditions that arise during the processing of C# statements and expression cause an exception in certain circumstances when the operation cannot be completed normally. Örneğin, bir tamsayı bölme işlemi (bölme işleci), System.DivideByZeroException payda sıfırsa bir oluşturur.For example, an integer division operation (Division operator) throws a System.DivideByZeroException if the denominator is zero. Bu şekilde gerçekleşebileceği çeşitli özel durumların listesi için bkz. ortak özel durum sınıfları .See Common Exception Classes for a list of the various exceptions that can occur in this way.

System. Exception sınıfıThe System.Exception class

System.ExceptionSınıfı tüm özel durumların temel türüdür.The System.Exception class is the base type of all exceptions. Bu sınıf, tüm özel durumların paylaştığı bazı önemli özelliklerine sahiptir:This class has a few notable properties that all exceptions share:

  • Message , string özel durum nedeninin okunabilir bir açıklamasını içeren türünün salt okunur bir özelliğidir.Message is a read-only property of type string that contains a human-readable description of the reason for the exception.
  • InnerException , türünde salt okunurdur bir özelliktir Exception .InnerException is a read-only property of type Exception. Değeri null değilse, geçerli özel duruma neden olan özel duruma başvurur; Yani, geçerli özel durum ' ı işleyen bir catch bloğunda oluşturulmuştur InnerException .If its value is non-null, it refers to the exception that caused the current exception—that is, the current exception was raised in a catch block handling the InnerException. Aksi takdirde, değeri null olur ve bu özel durumun başka bir özel durum nedeniyle kaynaklanmadığını gösterir.Otherwise, its value is null, indicating that this exception was not caused by another exception. Bu şekilde birlikte zincirleme olan özel durum nesnelerinin sayısı rastgele olabilir.The number of exception objects chained together in this manner can be arbitrary.

Bu özelliklerin değeri, için örnek oluşturucusuna yapılan çağrılarda belirtilebilir System.Exception .The value of these properties can be specified in calls to the instance constructor for System.Exception.

Özel durumlar nasıl işlenirHow exceptions are handled

Özel durumlar bir try deyimle (TRY ifadesiyle) işlenir.Exceptions are handled by a try statement (The try statement).

Bir özel durum oluştuğunda, sistem özel durumun catch çalışma zamanı türü tarafından belirlendiği şekilde özel durumu işleyebilen en yakın yan tümceyi arar.When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. İlk olarak, geçerli yöntem bir sözcüksel kapsayan bir ifade için aranır try ve TRY ifadesinin ilişkili catch yan tümceleri sırayla kabul edilir.First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. Başarısız olursa, geçerli yöntemi çağıran yöntem, try geçerli yönteme yapılan çağrının noktasını kapsayan bir sözcüksel kapsayan ifade için aranır.If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. Bu arama catch , geçerli özel durumu işleyebilen bir yan tümce bulunana kadar devam eder, aynı sınıfa sahip bir özel durum sınıfını veya oluşturulan özel durumun çalışma zamanı türünün bir temel sınıfını adlandırarak.This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. Bir catch özel durum sınıfı adı olmayan bir yan tümce herhangi bir özel durumu işleyebilir.A catch clause that doesn't name an exception class can handle any exception.

Eşleşen bir catch yan tümcesi bulunduğunda sistem, catch yan tümcesinin ilk ifadesine denetimi aktarmaya hazırlar.Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Catch yan tümcesinin yürütülmesi başlamadan önce, sistem öncelikle finally TRY deyimleriyle ilişkili olan tüm yan tümceleri özel durumu yakaladı.Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.

Eşleşen bir catch yan tümcesi bulunmazsa, iki işlemlerden biri oluşur:If no matching catch clause is found, one of two things occurs:

  • Eşleşen bir catch yan tümcesinin araması bir statik oluşturucuya (statik oluşturucular) veya statik alan başlatıcısına ulaşırsa, System.TypeInitializationException statik oluşturucunun çağrılmasını tetikleyen noktada bir oluşturulur.If the search for a matching catch clause reaches a static constructor (Static constructors) or static field initializer, then a System.TypeInitializationException is thrown at the point that triggered the invocation of the static constructor. Öğesinin iç özel durumu, System.TypeInitializationException başlangıçta oluşturulan özel durumu içerir.The inner exception of the System.TypeInitializationException contains the exception that was originally thrown.
  • Eşleşen catch yan tümceleri araması, ilk olarak iş parçacığını Başlatan koda ulaşırsa, iş parçacığının yürütülmesi sonlandırılır.If the search for matching catch clauses reaches the code that initially started the thread, then execution of the thread is terminated. Bu sonlandırmanın etkisi, uygulama tanımlı ' dır.The impact of such termination is implementation-defined.

Yıkıcı yürütme sırasında oluşan özel durumlar, özel bahsetmeye değer.Exceptions that occur during destructor execution are worth special mention. Yıkıcı yürütme sırasında bir özel durum oluşursa ve bu özel durum yakalanmadığında, bu yıkıcının yürütülmesi sonlandırılır ve taban sınıfının yok edicisi (varsa) çağırılır.If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. Temel sınıf yoksa (tür durumunda olduğu gibi object ) veya temel sınıf yok edicisi yoksa, özel durum atılır.If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

Ortak özel durum sınıflarıCommon Exception Classes

Aşağıdaki özel durumlar belirli C# işlemleri tarafından oluşturulur.The following exceptions are thrown by certain C# operations.

System.ArithmeticException Ve gibi aritmetik işlemler sırasında oluşan özel durumlar için temel sınıf System.DivideByZeroException System.OverflowException .A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException.
System.ArrayTypeMismatchException Saklı öğenin gerçek türü dizinin gerçek türüyle uyumlu olmadığı için bir dizide bir depo başarısız olduğunda oluşturulur.Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.
System.DivideByZeroException Bir integral değeri sıfıra bölme girişimi gerçekleştiğinde oluşturulur.Thrown when an attempt to divide an integral value by zero occurs.
System.IndexOutOfRangeException Sıfırdan küçük veya dizi sınırları dışında bir dizin aracılığıyla bir diziyi dizin oluşturma girişimi olduğunda oluşturulur.Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.
System.InvalidCastException Temel bir türden veya arabirimden türetilmiş bir türe açık bir dönüştürme çalışma zamanında başarısız olursa oluşturulur.Thrown when an explicit conversion from a base type or interface to a derived type fails at run time.
System.NullReferenceException nullBaşvuru, başvurulan nesnenin zorunlu olmasına neden olacak şekilde kullanıldığında oluşturulur.Thrown when a null reference is used in a way that causes the referenced object to be required.
System.OutOfMemoryException Bellek ayırma girişimi (aracılığıyla) başarısız olduğunda oluşturulur new .Thrown when an attempt to allocate memory (via new) fails.
System.OverflowException checkedBağlamdaki aritmetik işlem taştığında oluşturulur.Thrown when an arithmetic operation in a checked context overflows.
System.StackOverflowException Yürütme yığını çok fazla sayıda bekleyen Yöntem çağrısı ile tükendiğinde oluşturulur; genellikle çok derin veya sınırsız özyineleme göstergesi.Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion.
System.TypeInitializationException Statik bir Oluşturucu bir özel durum oluşturduğunda ve catch bunu yakalamak için hiçbir yan tümce yoksa oluşturulur.Thrown when a static constructor throws an exception, and no catch clauses exists to catch it.