C#--使用Finally

简介: C#中可以用try..catch..Finally进行异常处理,try后面跟要执行的语句,catch为如有异常,对异常进行处理,Finally做清理工作,这部分必须执行,如下示例: 1 /* 2 Example13_1.

C#中可以用try..catch..Finally进行异常处理,try后面跟要执行的语句,catch为如有异常,对异常进行处理,Finally做清理工作,这部分必须执行,如下示例:

 
 
1 /*
2 Example13_1.cs illustrates a try, catch, and finally block
3   */
4
5 using System;
6
7 class Example13_1
8 {
9
10 public static void Main()
11 {
12
13 try
14 {
15
16 // code that throws an exception
17 int zero = 0 ;
18 Console.WriteLine( " In try block: attempting division by zero " );
19 int myInt = 1 / zero; // throws the exception
20 Console.WriteLine( " You never see this message! " );
21
22 }
23 catch
24 {
25
26 // code that handles the exception
27 Console.WriteLine( " In catch block: an exception was thrown " );
28
29 }
30 finally
31 {
32
33 // code that does any cleaning up
34 Console.WriteLine( " In finally block: do any cleaning up here " );
35
36 }
37
38 }
39
40 }
相关文章
每日一道面试题之try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
每日一道面试题之try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
186 0
|
8月前
|
编译器
try{...}catch(){...}finally{...}语句你真的理解吗?
try{...}catch(){...}finally{...}语句你真的理解吗?
41 0
try catch finally,try 里面有 return,finally 还执行吗?
try catch finally,try 里面有 return,finally 还执行吗?
98 0
|
Java 编译器 数据库连接
如何使用 try-with-resources 代替try-catch-finally?
如何使用 try-with-resources 代替try-catch-finally?
try...catch中,catch加了return,后面的代码是不会执行的
try...catch中,catch加了return,后面的代码是不会执行的
113 0
|
Java
【学习笔记】【Java】try-catch-finally中,finally是在什么时候执行的:try结束、catch结束、return前
结论:try-catch-finally中,finally执行:try结束、catch结束、return前
207 0
【学习笔记】【Java】try-catch-finally中,finally是在什么时候执行的:try结束、catch结束、return前
|
Web App开发 JavaScript 前端开发
啊,似乎没有真正理解 try...catch...finally!
啊,似乎没有真正理解 try...catch...finally!
497 0
啊,似乎没有真正理解 try...catch...finally!
|
Java 程序员 编译器
技术大佬:我去,你竟然还在用 try–catch-finally
技术大佬:我去,你竟然还在用 try–catch-finally
131 0
技术大佬:我去,你竟然还在用 try–catch-finally
|
NoSQL Java 数据库连接
finally 和 return,到底谁先执行
经常有人面试被问到:finally 和 return,到底谁先执行呢?