简体   繁体   中英

Exception handling for WPF Application

I have a substanital WPF application set up as follows: Views, ViewModels, Business Objects and Dals, with a SQL Compact DB. Database calls are made via Linq2Sql. Application is single user. (one db per user).

Assuming that an exception occurs within the Dal during an CRUD operation or a user has deleted the database, where should the exception handling take place.

Also if for whatever reason a exception is raised within the View/ViewModel I don't want the system to crash. How should I handle this. Should I just inform the user that an error occurred and recreate the View/ViewModel so that the user can continue. The ViewModels only communicate to other ViewModels via Messenging (eg something needs to be refreshed).

In the OnStartup() method of your WPF application you can subscribe to the Application.Current.DispatcherUnhandledException exception event which allows you to record the exception, inform the user of the exception and suggest any remedies if appropriate, and cancel the termination of the application by setting e.Handled = true .

You should only cancel the termination of your application if you can remedy the cause of the exception, otherwise you will potentially leave the application in an undefined state.

simplest answer would be it really depends what exactly are the requirements of the applications.

Details: First of all you should do exceptional handling where ever there is a chance of an exceptional case. While performing a CRUD operation, while performing something in view model or while even creating views. User definitely won't like the application to crash. So the best thing to do is to handle the exception, customize the error message so that it can make sense to the user and show it to user so that s/he knows an error has been occurred. Also ask user what to do now(it really depends on application requirement again) but for example if databse file has been deleted ask user if he wants to create a new one or things like that

DB problems should be handled in your dal, the dal should inform someone about problem with messaging/events.

exceptions from view/view models should be caught inside this classes unless you have some mvvm framework like caliburn, that can ahndle this stuff independently. After catching exception a message should be sent to the shell/view manager that will handle the problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM