捕获异常及自定义异常类
来源:互联网 发布:最新社交软件 编辑:程序博客网 时间:2024/06/04 19:05
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 捕获异常
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入一个非负数:");
int number = Convert.ToInt32(Console.ReadLine());//可能产生格式异常
double root;
if (number < 0)
{
throw new NegativeNumberExeption();//可能产生负数开平方根的异常
// throw new NegativeNumberExeption("负数不能开平方!");//可能产生负数开平方根的异常
}
else
{
root = Math.Sqrt(number);
}
Console.WriteLine("结果:{0}", root);
}
catch (NegativeNumberExeption e)//捕获负数开平方根的异常
{
Console.WriteLine(e.Message);//属性message指出异常的内容
Console.WriteLine(e.StackTrace);//属性StackTrace指出异常产生在哪个位置
}
catch (FormatException e)//捕获格式异常
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
finally
{
Console.WriteLine("运算结束!");//finally :不管是否出现异常,都会运行
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 捕获异常
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入一个非负数:");
int number = Convert.ToInt32(Console.ReadLine());//可能产生格式异常
double root;
if (number < 0)
{
throw new NegativeNumberExeption();//可能产生负数开平方根的异常
// throw new NegativeNumberExeption("负数不能开平方!");//可能产生负数开平方根的异常
}
else
{
root = Math.Sqrt(number);
}
Console.WriteLine("结果:{0}", root);
}
catch (NegativeNumberExeption e)//捕获负数开平方根的异常
{
Console.WriteLine(e.Message);//属性message指出异常的内容
Console.WriteLine(e.StackTrace);//属性StackTrace指出异常产生在哪个位置
}
catch (FormatException e)//捕获格式异常
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
finally
{
Console.WriteLine("运算结束!");//finally :不管是否出现异常,都会运行
}
}
class NegativeNumberExeption : ApplicationException //自定义一个负数的异常
{
public NegativeNumberExeption() : base("对负数进行非法操作") { } //自行查看上一篇base关键字的用法
public NegativeNumberExeption(string message) : base(message) { }
}
}}
0 0
- 捕获异常及自定义异常类
- Python 自定义异常类,主动捕获异常,主动抛出异常
- Android自定义捕获异常
- 自定义全局异常捕获
- 自定义全局异常捕获
- 自定义异常捕获-CrashHandler
- 自定义捕获异常
- 自定义捕获全局异常
- 自定义捕获全局异常
- 《异常捕获及处理》
- 异常捕获及上传
- 异常捕获及处理
- 自定义异常类 ----- 异常的捕获和处理
- 异常捕获与自定义raise异常
- android自定义捕获全局异常
- Android自定义全局异常捕获
- JAVA中的自定义异常捕获
- Fragment viewPager 自定义 异常捕获
- xss_quiz
- 类型转换
- C\C++网络编程总结
- 4 判断成绩是否优秀
- 十一种排序算法整理(JAVA实现,持续更新中)
- 捕获异常及自定义异常类
- zookeeper 入门
- OOC 面向对象 C 语言编程实践
- 【OpenCV入门教程之十】 形态学图像处理(一):膨胀与腐蚀
- UICollectionView常用属性
- View的滑动
- 反向ajax
- Java数组及其内存分配
- jdk环境变量配置