-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Exception.xml
1203 lines (989 loc) · 85.6 KB
/
Exception.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<Type Name="Exception" FullName="System.Exception">
<TypeSignature Language="C#" Value="public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable" />
<TypeSignature Language="ILAsm" Value=".class public sequential ansi serializable beforefieldinit Exception extends System.Object implements class System.Runtime.InteropServices._Exception, class System.Runtime.Serialization.ISerializable" />
<TypeSignature Language="DocId" Value="T:System.Exception" />
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Base>
<BaseTypeName>System.Object</BaseTypeName>
</Base>
<Interfaces>
<Interface>
<InterfaceName>System.Runtime.InteropServices._Exception</InterfaceName>
</Interface>
<Interface>
<InterfaceName>System.Runtime.Serialization.ISerializable</InterfaceName>
</Interface>
</Interfaces>
<Attributes>
<Attribute>
<AttributeName>System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)</AttributeName>
</Attribute>
<Attribute>
<AttributeName>System.Runtime.InteropServices.ComDefaultInterface(typeof(System.Runtime.InteropServices._Exception))</AttributeName>
</Attribute>
<Attribute>
<AttributeName>System.Runtime.InteropServices.ComVisible(true)</AttributeName>
</Attribute>
</Attributes>
<Docs>
<summary>Represents errors that occur during application execution.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler.
In this section:
[Errors and exceptions](#Errors)
[Try/catch blocks](#TryCatch)
[Exception type features](#Features)
[Exception class properties](#Properties)
[Performance considerations](#Performance)
[Re-throwing an exception](#Rethrow)
[Choosing standard exceptions](#Standard)
[Implementing custom exceptions](#Custom)
<a name="Errors"></a>
## Errors and exceptions
Run-time errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.
- **Usage errors.** A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the <xref:System.Object.Equals%28System.Object%29?displayProperty=nameWithType> method in the following example assumes that the `obj` argument must always be non-null.
[!code-csharp[System.Exception.Class#4](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/usageerrors1.cs#4)]
[!code-vb[System.Exception.Class#4](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/usageerrors1.vb#4)]
The <xref:System.NullReferenceException> exception that results when `obj` is `null` can be eliminated by modifying the source code to explicitly test for null before calling the <xref:System.Object.Equals%2A?displayProperty=nameWithType> override and then re-compiling. The following example contains the corrected source code that handles a `null` argument.
[!code-csharp[System.Exception.Class#5](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/usageerrors2.cs#5)]
[!code-vb[System.Exception.Class#5](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/usageerrors2.vb#5)]
Instead of using exception handling for usage errors, you can use the <xref:System.Diagnostics.Debug.Assert%2A?displayProperty=nameWithType> method to identify usage errors in debug builds, and the <xref:System.Diagnostics.Trace.Assert%2A?displayProperty=nameWithType> method to identify usage errors in both debug and release builds. For more information, see [Assertions in Managed Code](/visualstudio/debugger/assertions-in-managed-code).
- **Program errors.** A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.
In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the <xref:System.DateTime.TryParseExact%2A?displayProperty=nameWithType> method, which returns a <xref:System.Boolean> value that indicates whether the parse operation succeeded, instead of using the <xref:System.DateTime.ParseExact%2A?displayProperty=nameWithType> method, which throws a <xref:System.FormatException> exception if the date string cannot be converted to a <xref:System.DateTime> value. Similarly, if a user tries to open a file that does not exist, you can first call the <xref:System.IO.File.Exists%2A?displayProperty=nameWithType> method to check whether the file exists and, if it does not, prompt the user whether he or she wants to create it.
In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a <xref:System.IO.StreamReader> object or calling the <xref:System.IO.File.Open%2A> method may throw a <xref:System.IO.FileNotFoundException> exception. In these cases, you should use exception handling to recover from the error.
- **System failures.** A system failure is a run-time error that cannot be handled programmatically in a meaningful way. For example, any method can throw an <xref:System.OutOfMemoryException> exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as <xref:System.AppDomain.UnhandledException?displayProperty=nameWithType> and call the <xref:System.Environment.FailFast%2A?displayProperty=nameWithType> method to log exception information and notify the user of the failure before the application terminates.
<a name="TryCatch"></a>
## Try/catch blocks
The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into `try` blocks and `catch` blocks. There can be one or more `catch` blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block.
If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a `try` statement and is called a `try` block. Application code that handles exceptions thrown by a `try` block is placed within a `catch` statement and is called a `catch` block. Zero or more `catch` blocks are associated with a `try` block, and each `catch` block includes a type filter that determines the types of exceptions it handles.
When an exception occurs in a `try` block, the system searches the associated `catch` blocks in the order they appear in application code, until it locates a `catch` block that handles the exception. A `catch` block handles an exception of type `T` if the type filter of the catch block specifies `T` or any type that `T` derives from. The system stops searching after it finds the first `catch` block that handles the exception. For this reason, in application code, a `catch` block that handles a type must be specified before a `catch` block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles `System.Exception` is specified last.
If none of the `catch` blocks associated with the current `try` block handle the exception, and the current `try` block is nested within other `try` blocks in the current call, the `catch` blocks associated with the next enclosing `try` block are searched. If no `catch` block for the exception is found, the system searches previous nesting levels in the current call. If no `catch` block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a `catch` block that handles the exception. The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. If the top of the call stack is reached without finding a `catch` block that handles the exception, the default exception handler handles it and the application terminates.
<a name="Features"></a>
## Exception type features
Exception types support the following features:
- Human-readable text that describes the error. When an exception occurs, the runtime makes a text message available to inform the user of the nature of the error and to suggest action to resolve the problem. This text message is held in the <xref:System.Exception.Message%2A> property of the exception object. During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. If no error message argument is supplied to the constructor, the default error message is used. For more information, see the <xref:System.Exception.Message%2A> property.
- The state of the call stack when the exception was thrown. The <xref:System.Exception.StackTrace%2A> property carries a stack trace that can be used to determine where the error occurs in the code. The stack trace lists all the called methods and the line numbers in the source file where the calls are made.
<a name="Properties"></a>
## Exception class properties
The <xref:System.Exception> class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: <xref:System.Exception.StackTrace%2A>, <xref:System.Exception.InnerException%2A>, <xref:System.Exception.Message%2A>, <xref:System.Exception.HelpLink%2A>, <xref:System.Exception.HResult%2A>, <xref:System.Exception.Source%2A>, <xref:System.Exception.TargetSite%2A>, and <xref:System.Exception.Data%2A>.
When a causal relationship exists between two or more exceptions, the <xref:System.Exception.InnerException%2A> property maintains this information. The outer exception is thrown in response to this inner exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Supplementary information about the exception can be stored as a collection of key/value pairs in the <xref:System.Exception.Data%2A> property.
The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the <xref:System.Resources.ResourceManager> class. For more information about localized resources, see the [Creating Satellite Assemblies](~/docs/framework/resources/creating-satellite-assemblies-for-desktop-apps.md) and [Packaging and Deploying Resources](~/docs/framework/resources/packaging-and-deploying-resources-in-desktop-apps.md) topics.
To provide the user with extensive information about why the exception occurred, the <xref:System.Exception.HelpLink%2A> property can hold a URL (or URN) to a help file.
The <xref:System.Exception> class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.
For a list of initial property values for an instance of the <xref:System.Exception> class, see the <xref:System.Exception.%23ctor%2A> constructors.
<a name="Performance"></a>
## Performance considerations
Throwing or handling an exception consumes a significant amount of system resources and execution time. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Instead, provide a retry mechanism so users can enter valid input. Nor should you use exceptions to handle usage errors. Instead, use [assertions](/visualstudio/debugger/assertions-in-managed-code) to identify and correct usage errors.
In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing.
<a name="Rethrow"></a>
## Re-throwing an exception
In many cases, an exception handler simply wants to pass the exception on to the caller. This most often occurs in:
- A class library that in turn wraps calls to methods in the .NET Framework class library or other class libraries.
- An application or library that encounters a fatal exception. The exception handler can log the exception and then re-throw the exception.
The recommended way to re-throw an exception is to simply use the [throw](~/docs/csharp/language-reference/keywords/throw.md) statement in C# and the [Throw](~/docs/visual-basic/language-reference/statements/throw-statement.md) statement in Visual Basic without including an expression. This ensures that all call stack information is preserved when the exception is propagated to the caller. The following example illustrates this. A string extension method, `FindOccurrences`, wraps one or more calls to <xref:System.String.IndexOf%28System.String%2CSystem.Int32%29?displayProperty=nameWithType> without validating its arguments beforehand.
[!code-csharp[System.Exception.Class#6](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/rethrow1.cs#6)]
[!code-vb[System.Exception.Class#6](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/rethrow1.vb#6)]
A caller then calls `FindOccurrences` twice. In the second call to `FindOccurrences`, the caller passes a `null` as the search string, which cases the <xref:System.String.IndexOf%28System.String%2CSystem.Int32%29?displayProperty=nameWithType> method to throw an <xref:System.ArgumentNullException> exception. This exception is handled by the `FindOccurrences` method and passed back to the caller. Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved.
[!code-csharp[System.Exception.Class#7](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/rethrow1.cs#7)]
[!code-vb[System.Exception.Class#7](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/rethrow1.vb#7)]
In contrast, if the exception is re-thrown by using the
```csharp
throw e
```
```vb
Throw e
```
statement, the full call stack is not preserved, and the example would generate the following output:
```Output
'a' occurs at the following character positions: 4, 7, 15
An exception (ArgumentNullException) occurred.
Message:
Value cannot be null.
Parameter name: value
Stack Trace:
at Library.FindOccurrences(String s, String f)
at Example.Main()
```
A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. The caller can then use the new exception's <xref:System.Exception.InnerException%2A> property to retrieve stack frame and other information about the original exception. In this case, the throw statement is:
[!code-csharp[System.Exception.Class#8](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/rethrow3.cs#8)]
[!code-vb[System.Exception.Class#8](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/rethrow3.vb#8)]
The user code that handles the exception has to know that the <xref:System.Exception.InnerException%2A> property contains information about the original exception, as the following exception handler illustrates.
[!code-csharp[System.Exception.Class#9](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/rethrow3.cs#9)]
[!code-vb[System.Exception.Class#9](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/rethrow3.vb#9)]
<a name="Standard"></a>
## Choosing standard exceptions
When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. You should use a standard exception type under these two conditions:
- You are throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). Typically, you would throw an exception such as <xref:System.ArgumentException>, <xref:System.ArgumentNullException>, <xref:System.InvalidOperationException>, or <xref:System.NotSupportedException>. The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information, see the <xref:System.Exception.Message%2A> property.
- You are handling an error that can be communicated to the caller with an existing .NET Framework exception. You should throw the most derived exception possible. For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an <xref:System.ComponentModel.InvalidEnumArgumentException> (the most derived class) rather than an <xref:System.ArgumentException>.
The following table lists common exception types and the conditions under which you would throw them.
|Exception|Condition|
|---------------|---------------|
|<xref:System.ArgumentException>|A non-null argument that is passed to a method is invalid.|
|<xref:System.ArgumentNullException>|An argument that is passed to a method is `null`.|
|<xref:System.ArgumentOutOfRangeException>|An argument is outside the range of valid values.|
|<xref:System.IO.DirectoryNotFoundException>|Part of a directory path is not valid.|
|<xref:System.DivideByZeroException>|The denominator in an integer or <xref:System.Decimal> division operation is zero.|
|<xref:System.IO.DriveNotFoundException>|A drive is unavailable or does not exist.|
|<xref:System.IO.FileNotFoundException>|A file does not exist.|
|<xref:System.FormatException>|A value is not in an appropriate format to be converted from a string by a conversion method such as `Parse`.|
|<xref:System.IndexOutOfRangeException>|An index is outside the bounds of an array or collection.|
|<xref:System.InvalidOperationException>|A method call is invalid in an object's current state.|
|<xref:System.Collections.Generic.KeyNotFoundException>|The specified key for accessing a member in a collection cannot be found.|
|<xref:System.NotImplementedException>|A method or operation is not implemented.|
|<xref:System.NotSupportedException>|A method or operation is not supported.|
|<xref:System.ObjectDisposedException>|An operation is performed on an object that has been disposed.|
|<xref:System.OverflowException>|An arithmetic, casting, or conversion operation results in an overflow.|
|<xref:System.IO.PathTooLongException>|A path or file name exceeds the maximum system-defined length.|
|<xref:System.PlatformNotSupportedException>|The operation is not supported on the current platform.|
|<xref:System.RankException>|An array with the wrong number of dimensions is passed to a method.|
|<xref:System.TimeoutException>|The time interval allotted to an operation has expired.|
|<xref:System.UriFormatException>|An invalid Uniform Resource Identifier (URI) is used.|
<a name="Custom"></a>
## Implementing custom exceptions
In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:
- When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.
- When the exception requires handling that is different from the handling that is appropriate for an existing .NET Framework exception, or the exception must be disambiguated from a similar exception. For example, if you throw an <xref:System.ArgumentOutOfRangeException> exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method.
The <xref:System.Exception> class is the base class of all exceptions in the .NET Framework. Many derived classes rely on the inherited behavior of the members of the <xref:System.Exception> class; they do not override the members of <xref:System.Exception>, nor do they define any unique members.
To define your own exception class:
1. Define a class that inherits from <xref:System.Exception>. If necessary, define any unique members needed by your class to provide additional information about the exception. For example, the <xref:System.ArgumentException> class includes a <xref:System.ArgumentException.ParamName%2A> property that specifies the name of the parameter whose argument caused the exception, and the <xref:System.Text.RegularExpressions.RegexMatchTimeoutException> property includes a <xref:System.Text.RegularExpressions.RegexMatchTimeoutException.MatchTimeout%2A> property that indicates the time-out interval.
2. If necessary, override any inherited members whose functionality you want to change or modify. Note that most existing derived classes of <xref:System.Exception> do not override the behavior of inherited members.
3. Determine whether your custom exception object is serializable. Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. To make the exception object serializable, mark it with the <xref:System.SerializableAttribute> attribute.
4. Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors:
- <xref:System.Exception.%23ctor>, which uses default values to initialize the properties of a new exception object.
- <xref:System.Exception.%23ctor%28System.String%29>, which initializes a new exception object with a specified error message.
- <xref:System.Exception.%23ctor%28System.String%2CSystem.Exception%29>, which initializes a new exception object with a specified error message and inner exception.
- <xref:System.Exception.%23ctor%28System.Runtime.Serialization.SerializationInfo%2CSystem.Runtime.Serialization.StreamingContext%29>, which is a `protected` constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable.
The following example illustrates the use of a custom exception class. It defines a `NotPrimeException` exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. The exception defines a new property, `NonPrime`, that returns the non-prime number that caused the exception. Besides implementing a protected parameterless constructor and a constructor with <xref:System.Runtime.Serialization.SerializationInfo> and <xref:System.Runtime.Serialization.StreamingContext> parameters for serialization, the `NotPrimeException` class defines three additional constructors to support the `NonPrime` property. Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. The `NotPrimeException` class is also marked with the <xref:System.SerializableAttribute> attribute.
[!code-csharp[System.Exception.Class#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/notprimeexception.cs#1)]
[!code-vb[System.Exception.Class#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/notprimeexception.vb#1)]
The `PrimeNumberGenerator` class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. The `GetPrimesFrom` method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a `NotPrimeException` if that lower limit is not a prime number.
[!code-csharp[System.Exception.Class#2](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/primenumbergenerator.cs#2)]
[!code-vb[System.Exception.Class#2](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/primenumbergenerator.vb#2)]
The following example makes two calls to the `GetPrimesFrom` method with non-prime numbers, one of which crosses application domain boundaries. In both cases, the exception is thrown and successfully handled in client code.
[!code-csharp[System.Exception.Class#3](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.class/cs/example.cs#3)]
[!code-vb[System.Exception.Class#3](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.class/vb/example.vb#3)]
## Windows Runtime and [!INCLUDE[net_v451](~/includes/net-v451-md.md)]
In [!INCLUDE[net_win8_profile](~/includes/net-win8-profile-md.md)] for [!INCLUDE[win8](~/includes/win8-md.md)], some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. Starting with the [!INCLUDE[net_v451](~/includes/net-v451-md.md)] and [!INCLUDE[win81](~/includes/win81-md.md)], the common language runtime continues to use the original <xref:System.Exception> object that was thrown unless that exception was modified in a non-.NET Framework stack frame.
## Examples
The following example demonstrates a `catch` block that is defined to handle <xref:System.ArithmeticException> errors. This `catch` block also catches <xref:System.DivideByZeroException> errors, because <xref:System.DivideByZeroException> derives from <xref:System.ArithmeticException> and there is no `catch` block explicitly defined for <xref:System.DivideByZeroException> errors.
[!code-cpp[CatchException#1](~/samples/snippets/cpp/VS_Snippets_CLR/CatchException/CPP/catchexception.cpp#1)]
[!code-csharp[CatchException#1](~/samples/snippets/csharp/VS_Snippets_CLR/CatchException/CS/catchexception.cs#1)]
[!code-vb[CatchException#1](~/samples/snippets/visualbasic/VS_Snippets_CLR/CatchException/VB/catchexception.vb#1)]
]]></format>
</remarks>
</Docs>
<Members>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public Exception ();" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.#ctor" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Parameters />
<Docs>
<summary>Initializes a new instance of the <see cref="T:System.Exception" /> class.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This constructor initializes the <xref:System.Exception.Message%2A> property of the new instance to a system-supplied message that describes the error and takes into account the current system culture.
All the derived classes should provide this default constructor. The following table shows the initial property values for an instance of <xref:System.Exception>.
|Property|Value|
|--------------|-----------|
|<xref:System.Exception.InnerException%2A>|A null reference (`Nothing` in Visual Basic).|
|<xref:System.Exception.Message%2A>|A system-supplied localized description.|
## Examples
The following code example derives an `Exception` that uses a predefined message. The code demonstrates the use of the parameterless constructor for the derived class and the base `Exception` class.
[!code-cpp[System.Exception.Ctor#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.Ctor/CPP/new.cpp#1)]
[!code-csharp[System.Exception.Ctor#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.Ctor/CS/new.cs#1)]
[!code-vb[System.Exception.Ctor#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.Ctor/VB/new.vb#1)]
]]></format>
</remarks>
</Docs>
</Member>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public Exception (string message);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(string message) cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.#ctor(System.String)" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Parameters>
<Parameter Name="message" Type="System.String" />
</Parameters>
<Docs>
<param name="message">The message that describes the error.</param>
<summary>Initializes a new instance of the <see cref="T:System.Exception" /> class with a specified error message.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This constructor initializes the <xref:System.Exception.Message%2A> property of the new instance by using the `message` parameter. If the `message` parameter is `null`, this is the same as calling the <xref:System.Exception.%23ctor%2A> constructor.
The following table shows the initial property values for an instance of <xref:System.Exception>.
|Property|Value|
|--------------|-----------|
|<xref:System.Exception.InnerException%2A>|A null reference (`Nothing` in Visual Basic).|
|<xref:System.Exception.Message%2A>|The error message string.|
## Examples
The following code example derives an `Exception` for a specific condition. The code demonstrates the use of the constructor that takes a caller-specified message as a parameter, for both the derived class and the base `Exception` class.
[!code-cpp[System.Exception.Ctor#2](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.Ctor/CPP/news.cpp#2)]
[!code-csharp[System.Exception.Ctor#2](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.Ctor/CS/news.cs#2)]
[!code-vb[System.Exception.Ctor#2](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.Ctor/VB/news.vb#2)]
]]></format>
</remarks>
</Docs>
</Member>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="protected Exception (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);" />
<MemberSignature Language="ILAsm" Value=".method familyhidebysig specialname rtspecialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>System.Security.SecuritySafeCritical</AttributeName>
</Attribute>
</Attributes>
<Parameters>
<Parameter Name="info" Type="System.Runtime.Serialization.SerializationInfo" />
<Parameter Name="context" Type="System.Runtime.Serialization.StreamingContext" />
</Parameters>
<Docs>
<param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
<param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
<summary>Initializes a new instance of the <see cref="T:System.Exception" /> class with serialized data.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream. For more information, see [XML and SOAP Serialization](~/docs/standard/serialization/xml-and-soap-serialization.md).
## Examples
The following code example defines a derived serializable `Exception` class. The code forces a divide-by-0 error and then creates an instance of the derived exception using the (<xref:System.Runtime.Serialization.SerializationInfo>, <xref:System.Runtime.Serialization.StreamingContext>) constructor. The code serializes the instance to a file, deserializes the file into a new exception, which it throws, and then catches and displays the exception's data.
[!code-cpp[System.Exception.GetObjectData#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.GetObjectData/CPP/getobjdata.cpp#1)]
[!code-csharp[System.Exception.GetObjectData#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.GetObjectData/CS/getobjdata.cs#1)]
[!code-vb[System.Exception.GetObjectData#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.GetObjectData/VB/getobjdata.vb#1)]
]]></format>
</remarks>
<exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is <see langword="null" />.</exception>
<exception cref="T:System.Runtime.Serialization.SerializationException">The class name is <see langword="null" /> or <see cref="P:System.Exception.HResult" /> is zero (0).</exception>
<altmember cref="T:System.Runtime.Serialization.SerializationInfo" />
<altmember cref="T:System.Runtime.Serialization.StreamingContext" />
</Docs>
</Member>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public Exception (string message, Exception innerException);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(string message, class System.Exception innerException) cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.#ctor(System.String,System.Exception)" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Parameters>
<Parameter Name="message" Type="System.String" />
<Parameter Name="innerException" Type="System.Exception" />
</Parameters>
<Docs>
<param name="message">The error message that explains the reason for the exception.</param>
<param name="innerException">The exception that is the cause of the current exception, or a null reference (<see langword="Nothing" /> in Visual Basic) if no inner exception is specified.</param>
<summary>Initializes a new instance of the <see cref="T:System.Exception" /> class with a specified error message and a reference to the inner exception that is the cause of this exception.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
An exception that is thrown as a direct result of a previous exception should include a reference to the previous exception in the <xref:System.Exception.InnerException%2A> property. The <xref:System.Exception.InnerException%2A> property returns the same value that is passed into the constructor, or a null reference (`Nothing` in Visual Basic) if the <xref:System.Exception.InnerException%2A> property does not supply the inner exception value to the constructor.
The following table shows the initial property values for an instance of <xref:System.Exception>.
|Property|Value|
|--------------|-----------|
|<xref:System.Exception.InnerException%2A>|The inner exception reference.|
|<xref:System.Exception.Message%2A>|The error message string.|
## Examples
The following code example derives an `Exception` for a specific condition. The code demonstrates the use of the constructor that takes a message and an inner exception as parameters, for both the derived class and the base `Exception` class.
[!code-cpp[System.Exception.Ctor#3](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.Ctor/CPP/newsi.cpp#3)]
[!code-csharp[System.Exception.Ctor#3](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.Ctor/CS/newsi.cs#3)]
[!code-vb[System.Exception.Ctor#3](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.Ctor/VB/newsi.vb#3)]
]]></format>
</remarks>
</Docs>
</Member>
<Member MemberName="Data">
<MemberSignature Language="C#" Value="public virtual System.Collections.IDictionary Data { get; }" />
<MemberSignature Language="ILAsm" Value=".property instance class System.Collections.IDictionary Data" />
<MemberSignature Language="DocId" Value="P:System.Exception.Data" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>get: System.Security.SecuritySafeCritical</AttributeName>
</Attribute>
</Attributes>
<ReturnValue>
<ReturnType>System.Collections.IDictionary</ReturnType>
</ReturnValue>
<Docs>
<summary>Gets a collection of key/value pairs that provide additional user-defined information about the exception.</summary>
<value>An object that implements the <see cref="T:System.Collections.IDictionary" /> interface and contains a collection of user-defined key/value pairs. The default is an empty collection.</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
Use the <xref:System.Collections.IDictionary?displayProperty=nameWithType> object returned by the <xref:System.Exception.Data%2A> property to store and retrieve supplementary information relevant to the exception. The information is in the form of an arbitrary number of user-defined key/value pairs. The key component of each key/value pair is typically an identifying string, whereas the value component of the pair can be any type of object.
## Key/Value Pair Security
The key/value pairs stored in the collection returned by the <xref:System.Exception.Data%2A> property are not secure. If your application calls a nested series of routines, and each routine contains exception handlers, the resulting call stack contains a hierarchy of those exception handlers. If a lower-level routine throws an exception, any upper-level exception handler in the call stack hierarchy can read and/or modify the key/value pairs stored in the collection by any other exception handler. This means you must guarantee that the information in the key/value pairs is not confidential and that your application will operate correctly if the information in the key/value pairs is corrupted.
## Key Conflicts
A key conflict occurs when different exception handlers specify the same key to access a key/value pair. Use caution when developing your application because the consequence of a key conflict is that lower-level exception handlers can inadvertently communicate with higher-level exception handlers, and this communication might cause subtle program errors. However, if you are cautious you can use key conflicts to enhance your application.
## Avoiding Key Conflicts
Avoid key conflicts by adopting a naming convention to generate unique keys for key/value pairs. For example, a naming convention might yield a key that consists of the period-delimited name of your application, the method that provides supplementary information for the pair, and a unique identifier.
Suppose two applications, named Products and Suppliers, each has a method named Sales. The Sales method in the Products application provides the identification number (the stock keeping unit or SKU) of a product. The Sales method in the Suppliers application provides the identification number, or SID, of a supplier. Consequently, the naming convention for this example yields the keys, "Products.Sales.SKU" and "Suppliers.Sales.SID".
## Exploiting Key Conflicts
Exploit key conflicts by using the presence of one or more special, prearranged keys to control processing. Suppose, in one scenario, the highest level exception handler in the call stack hierarchy catches all exceptions thrown by lower-level exception handlers. If a key/value pair with a special key exists, the high-level exception handler formats the remaining key/value pairs in the <xref:System.Collections.IDictionary> object in some nonstandard way; otherwise, the remaining key/value pairs are formatted in some normal manner.
Now suppose, in another scenario, the exception handler at each level of the call stack hierarchy catches the exception thrown by the next lower-level exception handler. In addition, each exception handler knows the collection returned by the <xref:System.Exception.Data%2A> property contains a set of key/value pairs that can be accessed with a prearranged set of keys.
Each exception handler uses the prearranged set of keys to update the value component of the corresponding key/value pair with information unique to that exception handler. After the update process is complete, the exception handler throws the exception to the next higher-level exception handler. Finally, the highest level exception handler accesses the key/value pairs and displays the consolidated update information from all the lower-level exception handlers.
## Examples
The following example demonstrates how to add and retrieve information using the <xref:System.Exception.Data%2A> property.
[!code-cpp[exception.data#1](~/samples/snippets/cpp/VS_Snippets_CLR/exception.data/CPP/data.cpp#1)]
[!code-csharp[exception.data#1](~/samples/snippets/csharp/VS_Snippets_CLR/exception.data/CS/data.cs#1)]
[!code-vb[exception.data#1](~/samples/snippets/visualbasic/VS_Snippets_CLR/exception.data/VB/data.vb#1)]
]]></format>
</remarks>
<altmember cref="T:System.Collections.DictionaryEntry" />
</Docs>
</Member>
<Member MemberName="GetBaseException">
<MemberSignature Language="C#" Value="public virtual Exception GetBaseException ();" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance class System.Exception GetBaseException() cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.GetBaseException" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.Exception</ReturnType>
</ReturnValue>
<Parameters />
<Docs>
<summary>When overridden in a derived class, returns the <see cref="T:System.Exception" /> that is the root cause of one or more subsequent exceptions.</summary>
<returns>The first exception thrown in a chain of exceptions. If the <see cref="P:System.Exception.InnerException" /> property of the current exception is a null reference (<see langword="Nothing" /> in Visual Basic), this property returns the current exception.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
A chain of exceptions consists of a set of exceptions such that each exception in the chain was thrown as a direct result of the exception referenced in its `InnerException` property. For a given chain, there can be exactly one exception that is the root cause of all other exceptions in the chain. This exception is called the base exception and its `InnerException` property always contains a null reference.
For all exceptions in a chain of exceptions, the `GetBaseException` method must return the same object (the base exception).
Use the `GetBaseException` method when you want to find the root cause of an exception but do not need information about exceptions that may have occurred between the current exception and the first exception.
## Examples
The following code example defines two derived `Exception` classes. It forces an exception and then throws it again with each of the derived classes. The code shows the use of the `GetBaseException` method to retrieve the original exception.
[!code-cpp[System.Exception.GetBaseException#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.GetBaseException/CPP/getbaseexc.cpp#1)]
[!code-csharp[System.Exception.GetBaseException#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.GetBaseException/CS/getbaseexc.cs#1)]
[!code-vb[System.Exception.GetBaseException#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.GetBaseException/VB/getbaseexc.vb#1)]
]]></format>
</remarks>
<block subset="none" type="overrides">
<para>The <see langword="GetBaseException" /> method is overridden in classes that require control over the exception content or format.</para>
</block>
</Docs>
</Member>
<Member MemberName="GetObjectData">
<MemberSignature Language="C#" Value="public virtual void GetObjectData (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>System.Security.SecurityCritical</AttributeName>
</Attribute>
</Attributes>
<ReturnValue>
<ReturnType>System.Void</ReturnType>
</ReturnValue>
<Parameters>
<Parameter Name="info" Type="System.Runtime.Serialization.SerializationInfo" />
<Parameter Name="context" Type="System.Runtime.Serialization.StreamingContext" />
</Parameters>
<Docs>
<param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
<param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
<summary>When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
`GetObjectData` sets a <xref:System.Runtime.Serialization.SerializationInfo> with all the exception object data targeted for serialization. During deserialization, the exception is reconstituted from the `SerializationInfo` transmitted over the stream.
## Examples
The following code example defines a derived serializable `Exception` class that implements `GetObjectData`, which makes minor changes to two properties and then calls the base class to perform the serialization. The example forces a divide-by-0 error and then creates an instance of the derived exception. The code serializes the instance to a file, deserializes the file into a new exception, which it throws, and then catches and displays the exception's data.
[!code-cpp[System.Exception.GetObjectData#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.GetObjectData/CPP/getobjdata.cpp#1)]
[!code-csharp[System.Exception.GetObjectData#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.GetObjectData/CS/getobjdata.cs#1)]
[!code-vb[System.Exception.GetObjectData#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.GetObjectData/VB/getobjdata.vb#1)]
]]></format>
</remarks>
<exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (<see langword="Nothing" /> in Visual Basic).</exception>
<permission cref="T:System.Security.SecurityCriticalAttribute">requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.</permission>
<altmember cref="T:System.Runtime.Serialization.SerializationInfo" />
<altmember cref="T:System.Runtime.Serialization.StreamingContext" />
</Docs>
</Member>
<Member MemberName="GetType">
<MemberSignature Language="C#" Value="public Type GetType ();" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance class System.Type GetType() cil managed" />
<MemberSignature Language="DocId" Value="M:System.Exception.GetType" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.Type</ReturnType>
</ReturnValue>
<Parameters />
<Docs>
<summary>Gets the runtime type of the current instance.</summary>
<returns>A <see cref="T:System.Type" /> object that represents the exact runtime type of the current instance.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The <xref:System.Exception.GetType%2A> method exists to support the .NET Framework infrastructure, and internally invokes the fundamental method, <xref:System.Object.GetType%2A?displayProperty=nameWithType>.
]]></format>
</remarks>
<altmember cref="T:System.Type" />
<altmember cref="T:System.Object" />
</Docs>
</Member>
<Member MemberName="HelpLink">
<MemberSignature Language="C#" Value="public virtual string HelpLink { get; set; }" />
<MemberSignature Language="ILAsm" Value=".property instance string HelpLink" />
<MemberSignature Language="DocId" Value="P:System.Exception.HelpLink" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.String</ReturnType>
</ReturnValue>
<Docs>
<summary>Gets or sets a link to the help file associated with this exception.</summary>
<value>The Uniform Resource Name (URN) or Uniform Resource Locator (URL).</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The return value, which represents a help file, is a URN or URL. For example, the `HelpLink` value could be:
"file:///C:/Applications/Bazzal/help.html#ErrorNum42"
## Examples
The following code example throws an `Exception` that sets the `HelpLink` property in its constructor and then catches the exception and displays `HelpLink`.
[!code-cpp[System.Exception.Properties#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.Properties/CPP/properties.cpp#1)]
[!code-csharp[System.Exception.Properties#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.Properties/CS/properties.cs#1)]
[!code-vb[System.Exception.Properties#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.Properties/VB/properties.vb#1)]
]]></format>
</remarks>
</Docs>
</Member>
<Member MemberName="HResult">
<MemberSignature Language="C#" Value="public int HResult { get; protected set; }" />
<MemberSignature Language="ILAsm" Value=".property instance int32 HResult" />
<MemberSignature Language="DocId" Value="P:System.Exception.HResult" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.Int32</ReturnType>
</ReturnValue>
<Docs>
<summary>Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.</summary>
<value>The HRESULT value.</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
HRESULT is a 32-bit value, divided into three different fields: a severity code, a facility code, and an error code. The severity code indicates whether the return value represents information, warning, or error. The facility code identifies the area of the system responsible for the error. The error code is a unique number that is assigned to represent the exception. Each exception is mapped to a distinct HRESULT. When managed code throws an exception, the runtime passes the HRESULT to the COM client. When unmanaged code returns an error, the HRESULT is converted to an exception, which is then thrown by the runtime. For information about HRESULT values and their corresponding .NET Framework exceptions, see [How to: Map HRESULTs and Exceptions](~/docs/framework/interop/how-to-map-hresults-and-exceptions.md). See [Common HRESULT Values](http://msdn.microsoft.com/library/windows/desktop/aa378137.aspx) in the Windows documentation for a list of the values you are most likely to encounter.
Starting with the [!INCLUDE[net_v45](~/includes/net-v45-md.md)], the <xref:System.Exception.HResult%2A> property's setter is protected, whereas its getter is public. In previous versions of the .NET Framework, both getter and setter are protected.
## Examples
The following code example defines a derived `Exception` class that sets the `HResult` property to a custom value in its constructor.
[!code-cpp[System.Exception.HResult#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.HResult/CPP/hresult.cpp#1)]
[!code-csharp[System.Exception.HResult#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.HResult/CS/hresult.cs#1)]
[!code-vb[System.Exception.HResult#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.HResult/VB/hresult.vb#1)]
]]></format>
</remarks>
</Docs>
</Member>
<Member MemberName="InnerException">
<MemberSignature Language="C#" Value="public Exception InnerException { get; }" />
<MemberSignature Language="ILAsm" Value=".property instance class System.Exception InnerException" />
<MemberSignature Language="DocId" Value="P:System.Exception.InnerException" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.Exception</ReturnType>
</ReturnValue>
<Docs>
<summary>Gets the <see cref="T:System.Exception" /> instance that caused the current exception.</summary>
<value>An object that describes the error that caused the current exception. The <see cref="P:System.Exception.InnerException" /> property returns the same value as was passed into the <see cref="M:System.Exception.#ctor(System.String,System.Exception)" /> constructor, or <see langword="null" /> if the inner exception value was not supplied to the constructor. This property is read-only.</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
When an exception `X` is thrown as a direct result of a previous exception `Y`, the <xref:System.Exception.InnerException%2A> property of `X` should contain a reference to `Y`.
Use the <xref:System.Exception.InnerException%2A> property to obtain the set of exceptions that led to the current exception.
You can create a new exception that catches an earlier exception. The code that handles the second exception can make use of the additional information from the earlier exception to handle the error more appropriately.
Suppose that there is a function that reads a file and formats the data from that file. In this example, as the code tries to read the file, an <xref:System.IO.IOException> is thrown. The function catches the <xref:System.IO.IOException> and throws a <xref:System.IO.FileNotFoundException>. The <xref:System.IO.IOException> could be saved in the <xref:System.Exception.InnerException%2A> property of the <xref:System.IO.FileNotFoundException>, enabling the code that catches the <xref:System.IO.FileNotFoundException> to examine the cause of the initial error.
The <xref:System.Exception.InnerException%2A> property, which holds a reference to the inner exception, is set upon initialization of the exception object.
## Examples
The following example demonstrates throwing and catching an exception that references an inner exception.
[!code-cpp[InnerEx#1](~/samples/snippets/cpp/VS_Snippets_CLR/InnerEx/CPP/innerex.cpp#1)]
[!code-csharp[InnerEx#1](~/samples/snippets/csharp/VS_Snippets_CLR/InnerEx/CS/innerex.cs#1)]
[!code-vb[InnerEx#1](~/samples/snippets/visualbasic/VS_Snippets_CLR/InnerEx/VB/innerex.vb#1)]
]]></format>
</remarks>
</Docs>
</Member>
<Member MemberName="Message">
<MemberSignature Language="C#" Value="public virtual string Message { get; }" />
<MemberSignature Language="ILAsm" Value=".property instance string Message" />
<MemberSignature Language="DocId" Value="P:System.Exception.Message" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.String</ReturnType>
</ReturnValue>
<Docs>
<summary>Gets a message that describes the current exception.</summary>
<value>The error message that explains the reason for the exception, or an empty string ("").</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
Error messages target the developer who is handling the exception. The text of the <xref:System.Exception.Message%2A> property should completely describe the error and, when possible, should also explain how to correct the error. Top-level exception handlers may display the message to end-users, so you should ensure that it is grammatically correct and that each sentence of the message ends with a period. Do not use question marks or exclamation points. If your application uses localized exception messages, you should ensure that they are accurately translated.
> [!IMPORTANT]
> Do not disclose sensitive information in exception messages without checking for the appropriate permissions.
The value of the <xref:System.Exception.Message%2A> property is included in the information returned by <xref:System.Exception.ToString%2A>.The <xref:System.Exception.Message%2A> property is set only when creating an <xref:System.Exception>. If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture.
## Windows Runtime and [!INCLUDE[net_v451](~/includes/net-v451-md.md)]
Starting with the [!INCLUDE[net_v451](~/includes/net-v451-md.md)] and [!INCLUDE[win81](~/includes/win81-md.md)], the fidelity of error messages from exceptions that are propagated from Windows Runtime types and members that are not part of the .NET Framework is improved. In particular, exception messages from Visual C++ component extensions (C++/CX) are now propagated back into .NET Framework <xref:System.Exception> objects.
## Examples
The following code example throws and then catches an <xref:System.Exception> Exception and displays the exception's text message using the <xref:System.Exception.Message%2A> property.
[!code-cpp[System.Exception.Properties#1](~/samples/snippets/cpp/VS_Snippets_CLR_System/system.Exception.Properties/CPP/properties.cpp#1)]
[!code-csharp[System.Exception.Properties#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Exception.Properties/CS/properties.cs#1)]
[!code-vb[System.Exception.Properties#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Exception.Properties/VB/properties.vb#1)]
]]></format>
</remarks>
<block subset="none" type="overrides">
<para>If you throw an exception from a property, and you need to refer in the text of <see cref="P:System.Exception.Message" /> to the property argument that you set or get, use "value" as the name of the property argument.</para>
</block>
<block subset="none" type="overrides">
<para>The <see cref="P:System.Exception.Message" /> property is overridden in classes that require control over message content or format. Application code typically accesses this property when it needs to display information about an exception that has been caught.
The error message should be localized.</para>
</block>
</Docs>
</Member>
<Member MemberName="SerializeObjectState">
<MemberSignature Language="C#" Value="protected event EventHandler<System.Runtime.Serialization.SafeSerializationEventArgs> SerializeObjectState;" />
<MemberSignature Language="ILAsm" Value=".event class System.EventHandler`1<class System.Runtime.Serialization.SafeSerializationEventArgs> SerializeObjectState" />
<MemberSignature Language="DocId" Value="E:System.Exception.SerializeObjectState" />
<MemberType>Event</MemberType>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.EventHandler<System.Runtime.Serialization.SafeSerializationEventArgs></ReturnType>
</ReturnValue>
<Docs>
<summary>Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The exception state object implements the <xref:System.Runtime.Serialization.ISafeSerializationData> interface.
When the <xref:System.Exception.SerializeObjectState> event is subscribed to, the exception is deserialized and created as an empty exception. The exception's constructor is not run, and the exception state is also deserialized. The <xref:System.Runtime.Serialization.ISafeSerializationData.CompleteDeserialization%2A> callback method of the exception state object is then notified so that it can push deserialized data into the empty exception.
The <xref:System.Exception.SerializeObjectState> event enables transparent exception types to serialize and deserialize exception data. Transparent code can execute commands within the bounds of the permission set it is operating within, but cannot execute, call, derive from, or contain critical code.
If the <xref:System.Exception.SerializeObjectState> event is not subscribed to, deserialization occurs as usual using the <xref:System.Exception.%23ctor%2A> constructor.
Typically, a handler for the <xref:System.Exception.SerializeObjectState> event is added in the exception's constructor to provide for its serialization. But because the constructor is not executed when the <xref:System.Exception.SerializeObjectState> event handler executes, serializing a deserialized exception can throw a <xref:System.Runtime.Serialization.SerializationException> exception when you try to deserialize the exception. To avoid this, you should also add the handler for the <xref:System.Exception.SerializeObjectState> event in the <xref:System.Runtime.Serialization.ISafeSerializationData.CompleteDeserialization%2A?displayProperty=nameWithType> method. See the Examples section for an illustration.
## Examples
The following example defines a `BadDivisionException` that handles the <xref:System.Exception.SerializeObjectState> event. It also contains a state object, which is a nested structure named `BadDivisionExceptionState` that implements the <xref:System.Runtime.Serialization.ISafeSerializationData> interface.
[!code-csharp[System.Exception.SerializeObjectState#1](~/samples/snippets/csharp/VS_Snippets_CLR_System/system.exception.serializeobjectstate/cs/example2.cs#1)]
[!code-vb[System.Exception.SerializeObjectState#1](~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.exception.serializeobjectstate/vb/example2.vb#1)]
The `BadDivisionException` exception is thrown when a floating-point division by zero occurs. During the first division by zero, the example instantiates a `BadDivisionException` object, serializes it, and throws the exception. When subsequent divisions by zero occur, the example deserializes the previously serialized object, reserializes it, and throws the exception. To provide for object serialization, deserialization, reserialization, and deserialization, the example adds the <xref:System.Exception.SerializeObjectState> event handler both in the `BadDivisionException` class constructor and in the <xref:System.Runtime.Serialization.ISafeSerializationData.CompleteDeserialization%2A?displayProperty=nameWithType> implementation.
]]></format>
</remarks>
<block subset="none" type="overrides">
<para>If this event is subscribed to and used, all derived types that follow in the inheritance hierarchy must implement the same serialization mechanism.</para>
</block>
</Docs>
</Member>
<Member MemberName="Source">
<MemberSignature Language="C#" Value="public virtual string Source { get; set; }" />
<MemberSignature Language="ILAsm" Value=".property instance string Source" />
<MemberSignature Language="DocId" Value="P:System.Exception.Source" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyName>System.Runtime</AssemblyName>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyVersion>4.0.10.0</AssemblyVersion>
<AssemblyVersion>4.0.20.0</AssemblyVersion>
<AssemblyVersion>4.1.0.0</AssemblyVersion>
<AssemblyVersion>4.2.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>mscorlib</AssemblyName>
<AssemblyVersion>2.0.5.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.String</ReturnType>