C#note 05: Errors and Exception Handling

Errors and Exception Handling

When something goes wrong while a C# program is running, an exception occurs. Exceptions stop the current flow of the program, and if nothing is done, the program simply stops running. Exceptions can be caused by a bug in the program-for example, if a number is divided by zero- or can be a result of some unexpected input, such as a user selecting a file that doesn't exist. As a programmer, you need to allow your program to deal with these problems without crasing to a halt.

C# provides several keywords - try, catch, and finally- that allow programs to detect exceptions, deal with them, and continue running. They are a very useful tool for making your applications more reliable.

Try and Catch

The try and catch keywords are used together. Use try to enclose the block of code you are concerned might generate an exception, and catch to contain the code that will be executed if the exception occurs. 

It's a good programming practice to be specific about the type of exception your catch code is detecting. Each try can have multiple catch statements, each dealing with a different exception.

finally Blocks

Code contained in a finally block is always executed, whether or not an exception occurs. Use the finally block to make sure resources are returned: for example, to make sure that a file is closed.

Using Exception Handling

Exceptions aren't always a sigh that a catastrophic problem has occurred in your program. Often they are a convenient way of leaving a section of code that is no longer relevant, or a signal that a method has been unsuccessful. Many of the .NET Framework class methods create exceptions to warn of a particular condition. 

You can also cause your own exceptions using the throw keyword.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值