Sign in Join
Wiki copytemporary

Try: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Try

OldNewLine
1+Back to [[Reserved words]].
2+
3+The [[Reserved word|reserved word]] `try` is part of either a `try`..[[Finally|finally]] [[Block|block]] or a `try`..[[Except|except]] block.
4+
5+If an [[Exceptions|exception]] occurs while executing the code between `try` and `finally`, execution resumes at `finally`. If no exception occurs, the code between `finally` and [[End|end]] will be executed also.
6+
7+``` pascal
8+try
9+ // code that might generate an exception
10+finally
11+ // will always be executed as last statements
12+end;
13+```
14+
15+Whenever an exception occurs, the code between `except` and `end` will be executed.
16+
17+``` pascal
18+try
19+ // code that might generate an exception
20+except
21+ // will only be executed in case of an exception
22+ on E: EDatabaseError do
23+ ShowMessage( 'Database error: '+ E.ClassName + #13#10 + E.Message );
24+ on E: Exception do
25+ ShowMessage( 'Error: '+ E.ClassName + #13#10 + E.Message );
26+end;
27+```
28+
29+To handle exceptions with an `except` block **and** also run a `finally` block, nest one `try` block in another.
30+
31+``` pascal
32+try
33+ try
34+ // code dealing with database that might generate an exception
35+ except
36+ // will only be executed in case of an exception
37+ on E: EDatabaseError do
38+ ShowMessage( 'Database error: '+ E.ClassName + #13#10 + E.Message );
39+ on E: Exception do
40+ ShowMessage( 'Error: '+ E.ClassName + #13#10 + E.Message );
41+ end;
42+finally
43+ // clean up database-related resources
44+end;
45+```
46+
47+## See also
48+
49+- [[Raise]]
50+- [[On]]
51+- [[Exceptions]]
52+
53+---
54+*From the Free Pascal wiki, page "Try", as it stood on 2022-08-06 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history