本文整理汇总了C#中System.Exception类的典型用法代码示例。如果您正苦于以下问题:C# Exception类的具体用法?C# Exception怎么用?C# Exception使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Exception类属于System命名空间,在下文中一共展示了Exception类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch (ArithmeticException e)
{
Console.WriteLine($"ArithmeticException Handler: {e}");
}
catch (Exception e)
{
Console.WriteLine($"Generic Exception Handler: {e}");
}
}
}
输出:
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. at ExceptionTestClass.Main()
示例2: GetHashCode
//引入命名空间
using System;
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
public override bool Equals(object obj)
{
// This implementation contains an error in program logic:
// It assumes that the obj argument is not null.
Person p = (Person) obj;
return this.Name.Equals(p.Name);
}
}
public class Example
{
public static void Main()
{
Person p1 = new Person();
p1.Name = "John";
Person p2 = null;
// The following throws a NullReferenceException.
Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));
}
}
示例3: GetHashCode
//引入命名空间
using System;
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
public override bool Equals(object obj)
{
// This implementation handles a null obj argument.
Person p = obj as Person;
if (p == null)
return false;
else
return this.Name.Equals(p.Name);
}
}
public class Example
{
public static void Main()
{
Person p1 = new Person();
p1.Name = "John";
Person p2 = null;
Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));
}
}
输出:
p1 = p2: False
示例4: FindOccurrences
//引入命名空间
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public static class Library
{
public static int[] FindOccurrences(this String s, String f)
{
var indexes = new List<int>();
int currentIndex = 0;
try {
while (currentIndex >= 0 && currentIndex < s.Length) {
currentIndex = s.IndexOf(f, currentIndex);
if (currentIndex >= 0) {
indexes.Add(currentIndex);
currentIndex++;
}
}
}
catch (ArgumentNullException e) {
// Perform some action here, such as logging this exception.
throw;
}
return indexes.ToArray();
}
}
示例5: Main
public class Example
{
public static void Main()
{
String s = "It was a cold day when...";
int[] indexes = s.FindOccurrences("a");
ShowOccurrences(s, "a", indexes);
Console.WriteLine();
String toFind = null;
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine("Message:\n {0}\n", e.Message);
Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace);
}
}
private static void ShowOccurrences(String s, String toFind, int[] indexes)
{
Console.Write("'{0}' occurs at the following character positions: ",
toFind);
for (int ctr = 0; ctr < indexes.Length; ctr++)
Console.Write("{0}{1}", indexes[ctr],
ctr == indexes.Length - 1 ? "" : ", ");
Console.WriteLine();
}
}
输出:
'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 System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri ngComparison comparisonType) at Library.FindOccurrences(String s, String f) at Example.Main()
示例6: ShowOccurrences
try {
indexes = s.FindOccurrences(toFind);
ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
Console.WriteLine("An exception ({0}) occurred.",
e.GetType().Name);
Console.WriteLine(" Message:\n{0}", e.Message);
Console.WriteLine(" Stack Trace:\n {0}", e.StackTrace);
Exception ie = e.InnerException;
if (ie != null) {
Console.WriteLine(" The Inner Exception:");
Console.WriteLine(" Exception Name: {0}", ie.GetType().Name);
Console.WriteLine(" Message: {0}\n", ie.Message);
Console.WriteLine(" Stack Trace:\n {0}\n", ie.StackTrace);
}
}
输出:
'a' occurs at the following character positions: 4, 7, 15 An exception (ArgumentNullException) occurred. Message: You must supply a search string. Stack Trace: at Library.FindOccurrences(String s, String f) at Example.Main() The Inner Exception: Exception Name: ArgumentNullException Message: Value cannot be null. Parameter name: value Stack Trace: at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri ngComparison comparisonType) at Library.FindOccurrences(String s, String f)
示例7: NotPrimeException
//引入命名空间
using System;
using System.Runtime.Serialization;
[Serializable()]
public class NotPrimeException : Exception
{
private int notAPrime;
protected NotPrimeException()
: base()
{ }
public NotPrimeException(int value) :
base(String.Format("{0} is not a prime number.", value))
{
notAPrime = value;
}
public NotPrimeException(int value, string message)
: base(message)
{
notAPrime = value;
}
public NotPrimeException(int value, string message, Exception innerException) :
base(message, innerException)
{
notAPrime = value;
}
protected NotPrimeException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{ }
public int NonPrime
{ get { return notAPrime; } }
}
示例8: PrimeNumberGenerator
//引入命名空间
using System;
using System.Collections.Generic;
[Serializable]
public class PrimeNumberGenerator
{
private const int START = 2;
private int maxUpperBound = 10000000;
private int upperBound;
private bool[] primeTable;
private List<int> primes = new List<int>();
public PrimeNumberGenerator(int upperBound)
{
if (upperBound > maxUpperBound)
{
string message = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound);
throw new ArgumentOutOfRangeException(message);
}
this.upperBound = upperBound;
// Create array and mark 0, 1 as not prime (True).
primeTable = new bool[upperBound + 1];
primeTable[0] = true;
primeTable[1] = true;
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound));
ctr++)
{
if (primeTable[ctr]) continue;
for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++)
if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true;
}
// Populate array with prime number information.
int index = START;
while (index != -1)
{
index = Array.FindIndex(primeTable, index, (flag) => !flag);
if (index >= 1)
{
primes.Add(index);
index++;
}
}
}
public int[] GetAllPrimes()
{
return primes.ToArray();
}
public int[] GetPrimesFrom(int prime)
{
int start = primes.FindIndex((value) => value == prime);
if (start < 0)
throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime));
else
return primes.FindAll((value) => value >= prime).ToArray();
}
}
示例9: Main
//引入命名空间
using System;
using System.Reflection;
class Example
{
public static void Main()
{
int limit = 10000000;
PrimeNumberGenerator primes = new PrimeNumberGenerator(limit);
int start = 1000001;
try
{
int[] values = primes.GetPrimesFrom(start);
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit);
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
AppDomain domain = AppDomain.CreateDomain("Domain2");
PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap(
typeof(Example).Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
new object[] { 1000000 }, null, null);
try
{
start = 100;
Console.WriteLine(gen.GetPrimesFrom(start));
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
}
}