Форум по Delphi программированию

Delphi Sources



Вернуться   Форум по Delphi программированию > Все о Delphi > Базы данных
Ник
Пароль
Регистрация <<         Правила форума         >> FAQ Пользователи Календарь Поиск Сообщения за сегодня Все разделы прочитаны

Ответ
 
Опции темы Поиск в этой теме Опции просмотра
  #1  
Старый 17.05.2011, 19:12
Аватар для TolAlik
TolAlik TolAlik вне форума
Прохожий
 
Регистрация: 02.10.2009
Сообщения: 41
Репутация: 10
Вопрос Обработка исключений

Здрасте! В одной из тем приводили код по обработке дублирующейся записи в базе. Код ниже:
Код:
procedure TForm1.ADOTable1PostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction);
begin
 ShowMessage('Такое имя уже есть');
 Action := daAbort;
end;
Но этот код работает для всех исключений, которые вызывают ограничивания у таблиц.
Как нужно доработать код для обработки конкретной ошибки, а то что то я не пойму как это делать? И как их между собой различать?
Заранее спасиб.
Ответить с цитированием
  #2  
Старый 17.05.2011, 19:36
Аватар для NumLock
NumLock NumLock вне форума
Let Me Show You
 
Регистрация: 30.04.2010
Адрес: Северодвинск
Сообщения: 5,426
Версия Delphi: 7, XE5
Репутация: 59586
По умолчанию

Цитата:
Сообщение от TolAlik
Здрасте! В одной из тем приводили код по обработке дублирующейся записи в базе. Код ниже:
Код:
procedure TForm1.ADOTable1PostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction);
begin
 ShowMessage('Такое имя уже есть');
 Action := daAbort;
end;
Но этот код работает для всех исключений, которые вызывают ограничивания у таблиц.
Как нужно доработать код для обработки конкретной ошибки, а то что то я не пойму как это делать? И как их между собой различать?
Заранее спасиб.
имхо, так.
__________________
Пишу программы за еду.
__________________
Ответить с цитированием
  #3  
Старый 17.05.2011, 19:39
Аватар для TolAlik
TolAlik TolAlik вне форума
Прохожий
 
Регистрация: 02.10.2009
Сообщения: 41
Репутация: 10
По умолчанию

А можно пример привести? а то я уже ни чего не понимаю?)
Ответить с цитированием
  #4  
Старый 17.05.2011, 20:15
Аватар для NumLock
NumLock NumLock вне форума
Let Me Show You
 
Регистрация: 30.04.2010
Адрес: Северодвинск
Сообщения: 5,426
Версия Delphi: 7, XE5
Репутация: 59586
По умолчанию

из файла справки:
Цитата:
Try...except statements
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.
__________________
Пишу программы за еду.
__________________
Ответить с цитированием
  #5  
Старый 20.05.2011, 09:48
Аватар для anonymous
anonymous anonymous вне форума
Новичок
 
Регистрация: 19.01.2011
Сообщения: 61
Версия Delphi: Delphi2009 v.12
Репутация: 12
По умолчанию

Дублирующаяся запись в базе - ошибка?
Ответить с цитированием
  #6  
Старый 22.05.2011, 13:43
Аватар для TolAlik
TolAlik TolAlik вне форума
Прохожий
 
Регистрация: 02.10.2009
Сообщения: 41
Репутация: 10
По умолчанию

Цитата:
из файла справки:
Try...except statements
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
Если честно я французский и немецкий учил . И я в базах полный чайник
Цитата:
anonymous Дублирующаяся запись в базе - ошибка?
Почти, но не то. Я наверно не правильно объяснил в чем проблема(((
Есть таблица:
Код:
create table man(id integer not null constraint Name_1 primary key,
FIO varchar(30) not null,	
holiday data not null,
phone numeric(11,0) not null,
pol varchar(1) not null constraint Name_2 check((pol = 'М') or (pol = 'Ж')), 
constraint Name_3 unique(FIO,holiday));
как можно в клиентском приложении, в блоке
Код:
try except 
распознать срабатывающие ограничения Name_1, Name_2 и Name_3 между собой на не допустимые значения?
Потому что в EDatabaseError срабатывает для всех ограничений одинаково:
Код:
on E:EDatabaseError do
   MessageDlg('Ошибка добавления!'+#13+E.Message,mtError,[mbOK],0);
А мне бы хотелось для каждого ограничения выдавать свое сообщение на русском языке.
Это вообще возможно?
Ответить с цитированием
  #7  
Старый 22.05.2011, 14:20
Аватар для TolAlik
TolAlik TolAlik вне форума
Прохожий
 
Регистрация: 02.10.2009
Сообщения: 41
Репутация: 10
По умолчанию

Вычитал в одной статье, что на FIBPlus есть компонент для такого рода дел под названием TpFIBErrorHandler, там даже целая статья посвящена тому как пользоваться этим компонентом и как обработку для любых constraint'ов делать.
А для InterBase есть что то подобное????
Ответить с цитированием
  #8  
Старый 23.05.2011, 16:20
Аватар для anonymous
anonymous anonymous вне форума
Новичок
 
Регистрация: 19.01.2011
Сообщения: 61
Версия Delphi: Delphi2009 v.12
Репутация: 12
По умолчанию

Try Except это обработка исключительных ситуаций.

Когда база отключена например, или когда типу integr хотят присвоить значение 'Пепяка'

TpFIBErrorHandler то что то вроде этого, но для ошибок именно в работе с фаербёрдом.Причем да, там есть возможность выбора типа обрабатываемых ошибок (то же отключение базы, либо глумление над PK,ввода дублирующегося значения для уникального поля). Все это есть в компонентах Fibplus вроде.

Вам, насколько я понимаю, нужно проверять то что вы вводите на правильность, и если я понимаю правильно , то тут скорее нужен контроль вводимых значений.
Ответить с цитированием
Ответ


Delphi Sources

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB-коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход


Часовой пояс GMT +3, время: 16:24.


 

Сайт

Форум

FAQ

RSS лента

Прочее

 

Copyright © Форум "Delphi Sources" by BrokenByte Software, 2004-2023

ВКонтакте   Facebook   Twitter