Csharp/CSharp Tutorial/Language Basics/Custom Exception
Содержание
- 1 A custom exception with HelpLink and Source
- 2 Create your own exception class based on Exception
- 3 CustomException is an application exception that supports remoting.
- 4 Derived exceptions must appear before base class exceptions.
- 5 Extends Exception
- 6 Use a custom Exception
- 7 User-Defined Exception Classes
A custom exception with HelpLink and Source
<source lang="csharp">using System; public class CustomException : ApplicationException {
public CustomException(string Message) : base(Message) { this.HelpLink = "See the Readme.txt file"; this.Source = "My Program"; }
} class MainClass {
public static void Main() { try { Console.WriteLine("Throwing a new CustomException object"); throw new CustomException("My CustomException message"); } catch (CustomException e) { Console.WriteLine("HelpLink = " + e.HelpLink); Console.WriteLine("Message = " + e.Message); Console.WriteLine("Source = " + e.Source); Console.WriteLine("StackTrace = " + e.StackTrace); Console.WriteLine("TargetSite = " + e.TargetSite); } }
}</source>
Throwing a new CustomException object HelpLink = See the Readme.txt file Message = My CustomException message Source = My Program StackTrace = at MainClass.Main() TargetSite = Void Main()
Create your own exception class based on Exception
<source lang="csharp">using System; using System.Collections; public class MyException : Exception {
public MyException( String reason, Exception inner ) :base( reason, inner ) { }
} public class MainClass {
static void Main() { try { try { ArrayList list = new ArrayList(); list.Add( 1 ); Console.WriteLine( "Item 10 = {0}", list[10] ); } catch( ArgumentOutOfRangeException x ) { throw new MyException( "I"d rather throw this",x ) ; } finally { Console.WriteLine( "Cleaning up..." ); } } catch( Exception x ) { Console.WriteLine( x ); Console.WriteLine( "Done" ); } }
}</source>
Cleaning up... MyException: I"d rather throw this ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at MainClass.Main() --- End of inner exception stack trace --- at MainClass.Main() Done
CustomException is an application exception that supports remoting.
<source lang="csharp">using System; using System.Reflection; using System.Runtime.Serialization; [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyCultureAttribute("")]
[Serializable] public class CustomException : Exception {
public CustomException(): base("custom exception", null) { prop_Time = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString(); } protected CustomException(SerializationInfo info,StreamingContext context) : base(info, context) { prop_Time = info.GetString("Time"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Time", prop_Time, typeof(string)); base.GetObjectData(info, context); } protected string prop_Time = null; public string Time { get { return prop_Time; } }
}</source>
Derived exceptions must appear before base class exceptions.
<source lang="csharp">using System;
class MyException : ApplicationException {
public MyException() : base() { } public MyException(string str) : base(str) { } public override string ToString() { return Message; }
}
class MyDerivedException : MyException {
public MyDerivedException() : base() { } public MyDerivedException(string str) : base(str) { } public override string ToString() { return Message; }
}
class MainClass {
public static void Main() { for(int x = 0; x < 3; x++) { try { if(x==0) throw new MyException("Caught an MyException exception"); else if(x==1) throw new MyDerivedException("Caught an MyDerivedException exception"); else throw new Exception(); } catch (MyDerivedException exc) { // catch the exception Console.WriteLine(exc); } catch (MyException exc) { // catch the exception Console.WriteLine(exc); } catch (Exception exc) { Console.WriteLine(exc); } } }
}</source>
Caught an MyException exception Caught an MyDerivedException exception System.Exception: Exception of type "System.Exception" was thrown. at MainClass.Main()
Extends Exception
<source lang="csharp">using System; using System.Runtime.Serialization; [Serializable] public sealed class MyException : Exception {
private string stringInfo; private bool booleanInfo; public MyException() : base() { } public MyException(string message) : base(message) { } public MyException(string message, Exception inner): base(message, inner) { } private MyException(SerializationInfo info, StreamingContext context) : base(info, context) { stringInfo = info.GetString("StringInfo"); booleanInfo = info.GetBoolean("BooleanInfo"); } public MyException(string message, string stringInfo, bool booleanInfo) : this(message) { this.stringInfo = stringInfo; this.booleanInfo = booleanInfo; } public MyException(string message, Exception inner, string stringInfo, bool booleanInfo): this(message, inner) { this.stringInfo = stringInfo; this.booleanInfo = booleanInfo; } public string StringInfo { get { return stringInfo; } } public bool BooleanInfo { get { return booleanInfo; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("StringInfo", stringInfo); info.AddValue("BooleanInfo", booleanInfo); base.GetObjectData(info, context); } public override string Message { get { string message = base.Message; if (stringInfo != null) { message += Environment.NewLine + stringInfo + " = " + booleanInfo; } return message; } }
} public class MainClass {
public static void Main() { try { throw new MyException("Some error", "SomeCustomMessage", true); } catch (MyException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.BooleanInfo); Console.WriteLine(ex.StringInfo); } }
}</source>
Some error SomeCustomMessage = True True SomeCustomMessage
Use a custom Exception
<source lang="csharp">using System;
class RangeArrayException : ApplicationException {
public RangeArrayException() : base() { } public RangeArrayException(string str) : base(str) { } public override string ToString() { return Message; }
}
class MainClass {
public static void Main() { try { throw new RangeArrayException("Low index not less than high."); } catch (RangeArrayException exc) { Console.WriteLine(exc); } }
}</source>
Low index not less than high.
User-Defined Exception Classes
<source lang="csharp">using System; public class CountIsZeroException: ApplicationException{
public CountIsZeroException(){ } public CountIsZeroException(string message) : base(message) { } public CountIsZeroException(string message, Exception inner) : base(message, inner) { }
} class MainClass{
public static void Main() { try { DoAverage(); } catch (CountIsZeroException e) { Console.WriteLine("CountIsZeroException: {0}", e); } } public static void DoAverage() { throw(new CountIsZeroException("Zero count in DoAverage")); }
}</source>
CountIsZeroException: CountIsZeroException: Zero count in DoAverage at MainClass.DoAverage() at MainClass.Main()