using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
Console.WriteLine("请输被除数:");
int a=int.Parse(Console.ReadLine());
Console.WriteLine("请输除数:");
int b=int.Parse(Console.ReadLine());
try
{
int z = a / b;
}
catch (DivideByZeroException e)
{
Console.Write("除数不能为0哦,亲" + e.Message);
}
finally
{
Console.Write("无论是否有异常,finally都会出现!");
}
Console.ReadKey();
}
}
2、数组越界
IndexOutOfRangeException
using System;
namespace ArrayException
{
class Array
{
public void CalculateSum()
{
int sum = 0;
int[] number = new int [5]{1,1,1,1,1};
try
{
for (int i=1;i<=5;i++)
{
sum = sum + number[i];
}
Console.WriteLine("The sum of the array is : {0} ",sum);
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine("Index was outside the bounds of the array!");
}
}
}
class test
{
public static void Main(string[] args)
{
Array obj=new Array();
obj.CalculateSum();
Console.ReadLine();
}
}
}
3、溢出异常
OverFlowException
using System;
class stack
{
public static void over1()
{
try
{
throw new StackOverflowException();
}
catch (StackOverflowException e)
{
Console.WriteLine(e.Message);
}
}
public static void over2()
{
try
{
over(10);
}
catch (StackOverflowException e)
{
Console.WriteLine(e.Message);
}
}
public static int over(int p)
{
return 10 + over(p+10);
}
public static void Main(string[] args)
{
over1();
over2();
//Console.WriteLine("异常的处理");
Console.ReadKey();
}
}
4、格式不正确
FormatException
using System;
using System.Collections.Generic;
public class ExceptionTest {
public static void Main(String[] args) {
String s = "cat miaomiao";
try {
int a=int.Parse(s);
} catch (FormatException e) {
Console.WriteLine("无法将该字符串转换为数字!");
Console.ReadKey();
}
}
}
5、finally练习
6、throw练习
using System;
using System.Collections.Generic;
using System.Text;
public class TEApp
{
public static void ThrowException()
{
throw new Exception();
}
public static void Main()
{
try
{
ThrowException();
Console.WriteLine("try");
}
catch (Exception e)
{
Console.WriteLine("catch");
}
finally
{
Console.WriteLine("finally");
}
Console.ReadLine();
}
}
7、自定义异常
using System;
public class EmailException:ApplicationException
{
public EmailException(string e): base(e){}
}
class Program
{
static void Main()
{
Console.WriteLine("请输入Email地址");
string email = Console.ReadLine();
string[]substrings = email.Split('@');
try
{
if (substrings.Length != 2)
{
throw new EmailException("email地址错误");
}
else
{
Console.WriteLine("输入正确");
}
}
catch (EmailException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}