⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch14.htm

📁 delphi自学的好教材!特别适合刚刚起步学习delphi的人员!同样对使用者具有参考价值!
💻 HTM
📖 第 1 页 / 共 5 页
字号:
in this case. When you write your own code, you can raise exceptions of the exceptionclasses created by VCL or you can create your own exception classes. Let's say youhave an error code 111 for a particular type of error and that you have an exceptionclass named EMyException. In that case, you can write the raise statement like this:</P><P><PRE>raise EMyException.Create(`Error 111');</PRE><P>The compiler makes a copy of the object being raised and passes it on to the exceptstatement immediately following the try block (I'll get back to that in a moment).</P><P><H4>More on except</H4><P>As I said, for starters your involvement with exceptions will likely be in catchingVCL exceptions. If something goes wrong in a VCL component, VCL is going to raisean exception. If you do not handle the exception, VCL will handle it in the defaultmanner. Usually this means that a message box will be displayed that describes theerror that occurred. By catching these exceptions in your code, you can decide howthey should be handled rather than accepting the default behavior.</P><P>Take a look at Listing 14.2 again. Starting at line 12, you see this code:</P><P><PRE>except  Child.Close;  Application.MessageBox(    `This file is not a Windows image file.',    `Picture Viewer Error', MB_ICONHAND or MB_OK);  Exit;end;</PRE><P>The except keyword tells the compiler that you want to catch all exceptions ofany type. Because no case statement follows the except statement, the code in theexcept block will be executed regardless of the type of exception raised. This isconvenient if you don't know what type of exception a particular piece of code willraise or if you want to catch any and all exceptions regardless of the type. In thereal world, though, you will probably need to be more specific in what exceptionsyou catch.</P><P>Let's go back to Listing 14.2 again. The code on line 9 might raise an exceptionif the file the user is trying to open is not a graphics file. If that happens, VCLwill raise an EInvalidGraphic exception. You can catch that type of exception onlyand let all others be handled in the default manner. The code looks like this:</P><P><PRE>except  on EInvalidGraphic do begin    Child.Close;    Application.MessageBox(      `This file is not a Windows image file.',      `Picture Viewer Error', MB_ICONHAND or MB_OK);    Exit;  end;end;</PRE><P>Notice that this code is catching an EInvalidGraphic exception only. This is thepreferred method of catching exceptions. Now any exceptions of this type will becaught by the except block and all other exception types will be handled in the defaultmanner.</P><P>It is important to understand that when you catch an exception, code executioncontinues after executing the except block. One of the advantages to catching exceptionsis that you can recover from the exception and continue program execution. Noticethe Exit statement in the preceding code snippet. In this case, you don't want tocontinue code execution following the exception, so you exit the procedure afterhandling the exception.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> VCL will handle many types of exceptions automatically, but it cannot	account for every possibility. An exception that is not handled is called an <I>unhandled	exception</I>. If an unhandled exception occurs, Windows generates an error message	and your application is terminated. Try to anticipate what exceptions might occur	in your application and do your best to handle them. <HR></BLOCKQUOTE><H4>Multiple Exception Types</H4><P>You can catch multiple exception types in your except block. For example, sayyou have written code that calls some VCL methods and also calls some functions inyour program that might raise an exception. If a VCL EInvalidGraphic exception occurs,you want to handle it. In addition, your own code might raise an exception of typeEMyOwnException (a class you have written for handling exceptions). You want to handlethat exception in a different manner. Given that scenario, you write the code likethis:</P><P><PRE>try  OneOfMyFunctions;  Image.Picture.LoadFromFile(`test.bmp');  AnotherOfMyFunctions;except  on EInvalidGraphic do begin    { do some stuff }  end;  on EMyOwnException do begin    { do some stuff }  end;end;</PRE><PRE>In this case you are preparing to catch either a VCL EInvalidGraphic exception or your EMyOwnException. You want to handle each type of exception in a specific manner, so you catch each type of exception independently. </PRE><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> Creating your own exception handling class can be as simple as one	line of code:</P>	<PRE>type  EMyOwnException = class(Exception);</PRE></BLOCKQUOTE><PRE></PRE><BLOCKQUOTE>	<P>Often you create you own exception classes simply to distinguish the type of exception.	No additional code is required. <HR></BLOCKQUOTE><P>Note that in the preceding examples you are catching a VCL exception class, butyou aren't actually doing anything with the class instance passed to the except block.In this case you don't really care what information the EInvalidGraphic class containsbecause it is enough to simply know that the exception occurred.</P><P>To use the specific instance of the exception class passed to the except block,declare a variable for the exception class in the do statement--for example,</P><P><PRE>try  Image.Picture.LoadFromFile(`test.bmp');except  on E : EInvalidGraphic do begin    { do something with E }  end;end;</PRE><P>Here the variable E is declared as a pointer to the EInvalidGraphic class passedto the except block. You can then use E to access properties or methods of the EInvalidGraphicclass. Note that the variable E is valid only within the block where it is declared.You should check the online help for the specific type of VCL exception-<BR>handling class you are interested in for more information about what properties andmethods are available for that class.</P><BLOCKQUOTE>	<P><HR><strong>TIP:</strong> The VCL exception classes all have a Message property that contains	a textual description of the exception that occurred. You can use this property to	display a message to the user:</P>	<PRE>except  on E : EInvalidGraphic do begin    { do some stuff }    MessageDlg(E.Message, mtError, [mbOk], 0);  end;end;</PRE></BLOCKQUOTE><PRE></PRE><BLOCKQUOTE>	<P>Sometimes the VCL messages might not be descriptive enough for your liking. In	those cases you can create your own error message, but often the Message property	is sufficient. <HR></BLOCKQUOTE><H3><A NAME="Heading11"></A>Using finally</H3><P>The finally keyword defines a section of code that is called regardless of whetheran exception occurs. In other words, the code in the finally section will be calledif an exception is raised and will be called if no exception is raised. If you usea finally block, you cannot use except.</P><P>The primary reason to use finally is to ensure that all dynamically allocatedmemory is properly disposed of in the event an exception is raised--for example,</P><P><PRE>procedure TForm1.FormCreate(Sender: TObject);var  Buffer : Pointer;begin  Buffer := AllocMem(1024);  try    { Code here that might raise an exception. }  finally    FreeMem(Buffer);  end;end;</PRE><P>Here, the memory allocated for Buffer will always be freed properly regardlessof whether an exception is raised in the try block.</P><P><H3><A NAME="Heading12"></A>Catching Unhandled Exceptions at the <BR>Application Level</H3><P>Your application can also handle exceptions at the application level. TApplicationhas an event called OnException that will occur any time an unhandled exception israised in your application. By responding to this event, you can catch any exceptionsraised by your applications.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> This event occurs when an unhandled exception is raised. Any exceptions	you catch with try and except are handled; therefore, the OnException event will	not occur for those exceptions. <HR></BLOCKQUOTE><P>You hook the OnException event just like you do when hooking the OnHint eventlike you did earlier:</P><DL>	<DT></DT>	<DD><B>1. </B>Add a method declaration to the main form's class declaration:	<P></DL><BLOCKQUOTE>	<PRE>procedure MyOnException(Sender : TObject; E : Exception);</PRE></BLOCKQUOTE><PRE></PRE><DL>	<DT></DT>	<DD><B>2. </B>Add the method body to the main form's implementation section:	<P></DL><BLOCKQUOTE>	<PRE>procedure TForm1.MyOnException(Sender : TObject; E : Exception);begin</PRE>	<P><B>{ Do whatever necessary to handle the exception here. }</B></P>	<P>	<PRE>end;</PRE></BLOCKQUOTE><PRE></PRE><DL>	<DT></DT>	<DD><B>3. </B>Assign your MyOnException method to the OnException event of the Application	object:	<P></DL><BLOCKQUOTE>	<PRE>Application.OnException := MyOnException;</PRE></BLOCKQUOTE><PRE></PRE><P>Now your MyOnException method will be called when an unhandled exception occurs.</P><BLOCKQUOTE>	<P><HR><strong>CAUTION:</strong> If you do not handle an exception properly, you can lock up your	program and possibly even crash Windows. It is usually best to let VCL and Windows	handle exceptions unless you know exactly how to handle them. <HR></BLOCKQUOTE><P>The ShowException function can be used to display a message box that describesthe error that occurred. This function is usually called by the default OnExceptionhandler, but you can use it in your applications as well. One of the parameters ofthe OnException event handler is a pointer to an Exception object (Exception is VCL'sbase exception-handling class). To display the error message box, pass the Exceptionobject to the ShowException function:</P><P><PRE>procedure TForm1.MyOnException(Sender : TObject; E : Exception);begin  { Do whatever necessary to handle the exception here  { then display the error message. }  Application.ShowException(E);end;</PRE><P>Now the error message box is displayed just as it would be if VCL were dealingwith the unhandled exception.</P><P>As you can see, handling exceptions at the application level is an advanced exception-handlingtechnique and is not something you should attempt unless you know exactly what you'redoing.</P><P><H3><A NAME="Heading13"></A>Debugging and Exception Handling</H3><P>Simply put, debugging when using exception handling can be a bit of a pain. Eachtime an exception is raised, the debugger pauses program execution at the exceptblock just as if a breakpoint were set on that line. If the except block is in yourcode, the execution point is displayed as it would be if you had stopped at a breakpoint.You can restart the program again by clicking the Run button, or you can step throughyour code.</P><BLOCKQUOTE>	<P><HR>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -