"抛出"异常是触发整个异常处理过程的原因.
在正常执行过程中,程序中的行以循环和分支顺序执行.当发生某种错误时,会创建一个异常然后抛出异常.
抛出的异常将修改程序中的常规操作顺序,使得在某个"catch"块内处理异常之前不会执行"正常"指令.一旦在catch块中捕获到异常,并且执行该catch块中的代码("处理"异常),正常的程序执行将在catch块之后立即恢复.
// Do some stuff, an exception thrown here won't be caught.
try
{
// Do stuff
throw new InvalidOperationException("Some state was invalid.");
// Nothing here will be executed because the exception has been thrown
}
catch(InvalidOperationException ex) // Catch and handle the exception
{
// This code is responsible for dealing with the error condition
// that prompted the exception to be thrown. We choose to name
// the exception "ex" in this block.
}
// This code will continue to execute as usual because the exception
// has been handled.
Run Code Online (Sandbox Code Playgroud)