Add a real exception handler

Close #1590
Close #3200