Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2007.02.11;
Скачать: [xml.tar.bz2];

Вниз

Расскажите пожалуйста про RAISE и исключения   Найти похожие ветки 

 
WhiteBarin ©   (2007-01-26 09:42) [0]

Хотелось бы узнать про raise и исключения, как они обрабатываются, про глобальный обработчик исключений, как его настроить и как исключения лучше использовать


 
Сергей М. ©   (2007-01-26 09:54) [1]

Справку на тему "exceptions" уже проштудировал ? Там что-то не понятно ?


 
whitebarin ©   (2007-01-26 10:02) [2]

Да читал непонятно использование raise собственно и глобальна обработка исключений, если про глобальную я могу догадываться что обработчик настраивается и в одном месте происходит обработка всех возникших исключений то про raise особенно в таком примере я не пойму, не имею ввиду тот случай где raise используется с параметрами там понятно raise возбуждает исключение а зачем например здесь немного не пойму
try
y:=0;
x:=10/y;
//...
except
x:=0;
raise;
end;


 
Рамиль ©   (2007-01-26 10:13) [3]


> whitebarin ©   (26.01.07 10:02) [2]

Что бы X был нормальным, а исключение предаем дальше, его обработка не наше дело.


 
Ega23 ©   (2007-01-26 10:14) [4]


Exceptions are handled within try...except statements. For example,

try

 X := Y/Z;
except
 on EZeroDivide do HandleZeroDivide;
end;

This statement attempts to divide Y by Z, but calls a routine named HandleZeroDivide if an EZeroDivide exception is raised.
The syntax of a try...except statement is

try statements except exceptionBlock end

where statements is a sequence of statements (delimited by semicolons) and exceptionBlock is either

another sequence of statements or
a sequence of exception handlers, optionally followed by

else statements

An exception handler has the form

on identifier: type do statement

where identifier: is optional (if included, identifier can be any valid identifier), type is a type used to represent exceptions, and statement is any statement.
A try...except statement executes the statements in the initial statements list. If no exceptions are raised, the exception block (exceptionBlock) is ignored and control passes to the next part of the program.
If an exception is raised during execution of the initial statements list, either by a raise statement in the statements list or by a procedure or function called from the statements list, an attempt is made to “handle” the exception:

If any of the handlers in the exception block matches the exception, control passes to the first such handler. An exception handler “matches” an exception just in case the type in the handler is the class of the exception or an ancestor of that class.
If no such handler is found, control passes to the statement in the else clause, if there is one.
If the exception block is just a sequence of statements without any exception handlers, control passes to the first statement in the list.

If none of the conditions above is satisfied, the search continues in the exception block of the next-most-recently entered try...except statement that has not yet exited. If no appropriate handler, else clause, or statement list is found there, the search propagates to the next-most-recently entered try...except statement, and so forth. If the outermost try...except statement is reached and the exception is still not handled, the program terminates.

When an exception is handled, the stack is traced back to the procedure or function containing the try...except statement where the handling occurs, and control is transferred to the executed exception handler, else clause, or statement list. This process discards all procedure and function calls that occurred after entering the try...except statement where the exception is handled. The exception object is then automatically destroyed through a call to its Destroy destructor and control is passed to the statement following the try...except statement. (If a call to the Exit, Break, or Continue standard procedure causes control to leave the exception handler, the exception object is still automatically destroyed.)

In the example below, the first exception handler handles division-by-zero exceptions, the second one handles overflow exceptions, and the final one handles all other math exceptions. EMathError appears last in the exception block because it is the ancestor of the other two exception classes; if it appeared first, the other two handlers would never be invoked.

try

...
except
 on EZeroDivide do HandleZeroDivide;
 on EOverflow do HandleOverflow;
 on EMathError do HandleMathError;
end;

An exception handler can specify an identifier before the name of the exception class. This declares the identifier to represent the exception object during execution of the statement that follows on...do. The scope of the identifier is limited to that statement. For example,

try

...
except
 on E: Exception do ErrorDialog(E.Message, E.HelpContext);
end;

If the exception block specifies an else clause, the else clause handles any exceptions that aren’t handled by the block’s exception handlers. For example,

try

...
except
 on EZeroDivide do HandleZeroDivide;
 on EOverflow do HandleOverflow;
 on EMathError do HandleMathError;
else
 HandleAllOthers;
end;

Here, the else clause handles any exception that isn’t an EMathError.
An exception block that contains no exception handlers, but instead consists only of a list of statements, handles all exceptions. For example,

try

...
except
 HandleException;
end;

Here, the HandleException routine handles any exception that occurs as a result of executing the statements between try and except.


 
Ega23 ©   (2007-01-26 10:14) [5]


Sometimes you want to ensure that specific parts of an operation are completed, whether or not the operation is interrupted by an exception. For example, when a routine acquires control of a resource, it is often important that the resource be released, regardless of whether the routine terminates normally. In these situations, you can use a try...finally statement.
The following example shows how code that opens and processes a file can ensure that the file is ultimately closed, even if an error occurs during execution.

Reset(F);

try
...  // process file F
finally
 CloseFile(F);
end;

The syntax of a try...finally statement is

try statementList1 finally statementList2 end

where each statementList is a sequence of statements delimited by semicolons. The try...finally statement executes the statements in statementList1 (the try clause). If statementList1 finishes without raising exceptions, statementList2 (the finally clause) is executed. If an exception is raised during execution of statementList1, control is transferred to statementList2; once statementList2 finishes executing, the exception is re-raised. If a call to the Exit, Break, or Continue procedure causes control to leave statementList1, statementList2 is automatically executed. Thus the finally clause is always executed, regardless of how the try clause terminates.

If an exception is raised but not handled in the finally clause, that exception is propagated out of the try...finally statement, and any exception already raised in the try clause is lost. The finally clause should therefore handle all locally raised exceptions, so as not to disturb propagation of other exceptions.


 
Юрий Зотов ©   (2007-01-26 10:14) [6]

> whitebarin ©   (26.01.07 10:02) [2]

Иногда по логике программы нужно при возникновении исключения сначала-что-то сделать, а потом перевозбудить то же самое исключение. Для этого в секции except пишется просто raise.


 
Сергей М. ©   (2007-01-26 10:14) [7]


> зачем например здесь немного не пойму


Здесь вызовом raise возбуждается то самое исключение, которое было "поймано" в блоке except. Т.е. вызов raise допустим только в в блоке except.


 
whitebarin ©   (2007-01-26 10:21) [8]

А зачем его снова возбуждать? Это видимо для того чтобы его затем обработать, а разве в секции except мы его не обработали, применяя конструкцию TRY EXCEPT (локальный обработчик исключения) зачем его далее возбуждать почему нельзя обойтись просто без него
try
y:=0;
x:=10/y;
//...
except
x:=0;
end;
вот это не понятно, пожалуйста разъясните


 
Сергей М. ©   (2007-01-26 10:43) [9]


> whitebarin ©   (26.01.07 10:21) [8]



> зачем его далее возбуждать почему нельзя обойтись просто
> без него


Это же локальный обработчик исключения !

Зачастую некое исключение невозможно полностью обработать в лок.обработчике, тогда его перевозбуждают с целью обработки уровнем выше в цепочке вложенных try..except-блоков (явных или неявных).
Верхнеуровневый обработчик в этой цепочке является глобальным - он отвечает за обработку всех необработанных исключений.


 
whitebarin ©   (2007-01-26 11:00) [10]

Спасибо что помогли разобраться, все доступно объяснили



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2007.02.11;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.48 MB
Время: 0.041 c
2-1169597485
Riply
2007-01-24 03:11
2007.02.11
Использование функции MsgWaitForMultipleObjects


2-1168648733
Wind
2007-01-13 03:38
2007.02.11
ANSI >UNICODE


15-1169340589
IMHO
2007-01-21 03:49
2007.02.11
Модель распространения ПО


15-1169224186
Pasha L
2007-01-19 19:29
2007.02.11
Где мне можно чего нить почитать про ипользование прокси?


15-1169091964
Одя
2007-01-18 06:46
2007.02.11
Существуют ли программы перевода сишных макросов в Паскаль?





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский