Upload
ilmyggo
View
242
Download
4
Tags:
Embed Size (px)
Citation preview
Riktig feilhåndtering
...og ja, checked exceptions er skadelig
Trond Arve Wasskog – JavaZone 2008
0Feilhåndtering
� Exception handling done right (and yes, checked exceptions are not necessary!)
- Trond Arve - BEKK - Confluence
� [JavaSpecialists 162] - Exceptions in Java
� Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential
Classes > Exceptions)
� java.net: Exception-Handling Antipatterns
� java.net: Three Rules for Effective Exception Handling
� Java Exceptions Handling
� The Art and Craft of Great Software Architecture and Development: Java
Exception Handling Anti-Patterns
� Neal Gafter's blog: Closures for Java
� Neal Gafter's blog: Removing Language Features?
� Exception handling problems in Java, Part I
� Exception handling problems in Java, Part II
� Bruce Eckel's MindView, Inc: Does Java need Checked Exceptions?
� Exceptions in Java: Nothing exceptional about them - Java World
� News & Ideas Forum (Closed for new topic posts) - Failure and Exceptions
� The Trouble with Checked Exceptions
� BEKK forum :: View topic - Håndtering av exceptions - erfaringer/diskusjoner
� Thinking Inside a Bigger Box » A Hopeful Idea: The End of Checked
Exceptions?
� Should checked exceptions be removed from Java?
� The RedirectException - The Daily WTF
� Dont Use Exceptions For Flow Control
� Exception Patterns
� Exception Tunneling
� Checked Exceptions Are Of Dubious Value
� Octopull/Java: More Exceptional Java
� Java theory and practice: The exceptions debate
� James Gosling Chimes In on Checked Exceptions
� Exception handling - Wikipedia, the free encyclopedia
� cat /dev/random » Remove checked exceptions?
� Java's checked exceptions were a mistake (and here's what I would like to do
about it)
� DOTNET Archives -- November 2000, week 1 (#349)
� Java Practices -> Checked versus unchecked exceptions
� Java Exception Handling - BEKK - Confluence
� Java Exception Handling - BEKK - Confluence
� Feilhåndtering - Prosjektkvalitet - Confluence
� XO.NET-metoden - Unntakshåndtering - BEKK - Confluence
� The Coad Letter: Modeling and Design Edition, Issue 90, Exceptional Strategies
� Effective Java Exceptions
� cache:DxQf_u_Vue8J:dev2dev.bea.com/lpt/a/541 java exception design
strategies - Google-søk
� David Walend's Blog: Design For Exceptions
� SwTech.com - Java Design Patterns
� Single Sign On - Login
� Exception Patterns
� Page 2 - Framework Patterns: Exception Handling, Logging, and Tracing
� Alexander Klimetschek's Blog : Exception Handling Best Practices Part 1
� towards_xcptn_hndling.pdf (application/pdf Object)
� Andre's Java Links
� JForum - Få slutt på galskapen: Stem "ja" til å fjerne checked exceptions fra
Java
� Beware the dangers of generic Exceptions - Java World
� Designing with exceptions - Java World
� Forward - Tips and Guidelines for Programming Java GUI Applications
� warning unchecked exception - Google-søk
� Exception (Java 2 Platform SE v1.4.2)
� LISTSERV 15.0 - RMI-USERS Archives
� Google Answers: The origin of checked exceptions
� Java (programming language) - Wikipedia, the free encyclopedia
� Hacking Architect : Weblog
� Old News: Java Checked vs. Unchecked Exceptions « Bees Are Social By Nature
� Opinion: Exception Handling Debate is Back
� Manageability - The Exception Debate: Why Gosling and Hejlsberg are Both In
Error
� Mistaeks I Hav Made: Generic Throws: Another Little Java Idiom
� DataAccessException.gif (GIF Image, 916x397 pixels)
� Antonio Goncalves' Weblog
� A Test-Driven Exploration of the Advanced Features of EJB 3.0
Dårlig feilhåndtering er vanlig
1972
ReturnCodes
1964
On ErrorExceptions
1964 1972 1983 1992 1995 2001
ReturnCodes
On ErrorExceptions
1964 1972 1983 1992 1995 2001
ReturnCodes
On ErrorExceptions
Exceptions
1964 1972 1983 1992 1995 2001
ReturnCodes
On ErrorExceptions
Exceptions
CheckedExceptions
1964 1972 1983 1992 1995 2001
ReturnCodes
On ErrorExceptions
Exceptions
CheckedExceptions
Exceptions
Java Exceptions
Throwable
Java Exceptions
Throwable
Exception
Checked
Exceptions
Java Exceptions
Throwable
Exception
Runtime
ExceptionChecked
Exceptions
Unchecked
Exceptions
Java Exceptions
Throwable
Error Exception
Runtime
ExceptionVM Errors
(Unchecked)Checked
Exceptions
Unchecked
Exceptions
Et alternativt design
Throwable
Error Exception
VM Errors
<interface>
Unchecked
Exception
Unchecked
Exceptions
Checked
Exceptions
1Hvem bryr seg om feilhåndtering?
Brukeren er opptatt av at en feil har oppstått og at situasjonen er håndtert,
ikke hva som har skjedd
Forretningen forstår funksjonelle feil og vil unngå kritiske feil
Drift vil vite hva de skal gjøre med feilen
Utviklere vil vite hva som har skjedd, hvor, når, hvorfor, hvem, tilstand og kontekst
Feilhåndtering har ulike interessenter med sine spesifikke behov
Typisk er få representert som kravstillere
2Feilhåndtering
Hva kan man gjøre når en feil oppstår?
Ignorere?
Håndtere?
Prøv igjen?
Prøv et alternativ?
Avslutte forespørselen
Hvor skal feil håndteres?
Lokal feilhåndtering
Sentral feilhåndtering
De aller fleste applikasjoner er tjent med sentral feilhåndtering
Feilhåndtering vs feilretting
Hva skjer om en annen Exception
eller Error kastes?
Er det viktig at operasjonen eller
applikasjonen fungerer?
Feilhåndtering sørger for konsistens
Feilhåndtering er kritisk for applikasjonen
Automatisert feilretting er ofte komplekst, kostbart og risikabelt
Feilhåndtering er viktigere enn feilretting
3Tre feiltyper
Application Exception
System Exception
Programming Exception
a.k.aRuntimeException
Type Håndter Feilfiks og
utrulling
Prøv igjen?
Application
Exception
Mulig Nei Nei
System
Exception
Nei Nei Mulig
Programming
Exception
Nei Ja Nei
4Overordnet Design
Lettvekts exception-hierarki - Distribuert
Felles exception-klasser med feilkode - Sentralisert
AbstractException- Long id
ApplicationException SystemException
java.lang
RuntimeException
Hybrid – Sentrale exception-klasser, distribuert hierarki
AbstractException- Long id
ApplicationException SystemException
java.lang
RuntimeException
dd<System Exceptions>
dd<Application Exceptions>
AbstractException-Long id
- Map context
-----------------------------
addContext(key, value)
Rammeverk = Distribuert
Applikasjon = Sentralisert
5Checked Exceptions
Ondskapens akse
JimWaldo
JamesGosling
Ann Wollrath
There was a time when Oak and the earliest version of Java did not have checked exceptions. Exception handling was advisory, and it was an unsafe world out there. It was our group (Jim Waldo and I in particular :-) that recommended that there be exceptions checked by the compiler. Jim was quite persuasive in his arguments, telling of a world where robust code would reign. After some consideration, Java was retooled to have checked exceptions. Only those exceptions for which there was norecovery or reflect application errors would be unchecked (e.g.,OutOfMemoryError, NullPointerException respectively). And the world was safe again
-- Ann Wollrathhttp://archives.java.sun.com/cgi-bin/wa?A2=ind9901&L=RMI-USERS&P=R25037
Ringbærerne
Item 58: Use chekced exceptions for recoverable conditions
and runtime exceptions for programming errors
Item 59: Avoid unnecessary use of checked exceptions
-- Joshua Bloch
I believe the language could be simplified by treating all exception types as unchecked without breaking existing programs. This could also result in a simplification of future
language extensions and APIs. But would the language and
platform be better off without checked exceptions?
-- Neil Gafter
The overhead of checked exceptions was having the opposite effect of what was intended, something that can happen when
you experiment (and I now believe that checked exceptions were
an experiment based on what someone thought was a good idea,
and which I believed was a good idea until recently).
-- Bruce Eckel
Source: http://java.net/pub/pq/163
“Checked exceptions are gold. Developers that don't like them are those that are too lazy to actually
think about error cases.”
http://www.javaworld.com/javaforums/showflat.php?Cat=0&Number=35228&Main=2629
“Were all exceptions unchecked, no exceptions would be caught until the corresponding bugs
began to present themselves.”
http://www.javaworld.com/javaforums/showflat.php?Cat=0&Number=35228&Main=2629
“Checked exceptions seem like a really good idea at first…
However, the kind of code you must write around these things and
the common phenomenon of "swallowed" exceptions begins to
suggest there's a problem. ”
http://www.mindview.net/Etc/Discussions/CheckedExceptions
“I am so tired of all the comments singing the praise of checked
exceptions on a theoretical basis. I don’t care about what’s good in
theory!”
http://www.javaworld.com/community/?q=comment/reply/1128
“The HibernateException, which wraps most of the errors that can occur in a Hibernate
persistence layer, is an unchecked exception (it wasn't in older versions of Hibernate).
In our opinion, we shouldn't force the application developer to catch an
unrecoverable exception at a low layer. In most systems, unchecked and fatal exceptions
are handled in one of the first frames of the method call stack”
http://www.hibernate.org/hib_docs/reference/en/html/transactions.html
Checked exceptions forurenser APIet
Checked exceptions fører til unnamanøvre som forpester
koden
Checked exceptions påtvinger lokal ”feilhåndtering”
java.text.ParseException
java.net.MalformedURLException
java.lang.CloneNotSupportedException
Checked exceptions kan brukes når klienten alltid både kan og må
håndtere feilen.
God feilhåndtering er viktig
Exceptions er bra
Dokumenter feilsituasjoner
Skal kompilatoren påtvinge feilhåndtering?
Checked exceptions påfører applikasjoner stor skade
Checked exceptions bør fjernes
6Slik, ikke slik!
Ikke bruk exceptions for normal forretningslogikk
Bruk eksisterende exceptions
IllegalStateExceptionUnsupportedOperationException
IllegalArgumentExceptionNoSuchElementException
NullPointerException
Ikke sluk exceptions
Fallgruver med try-catch-finally
Dokumenter exceptions
Russisk kone
ERROR [btpool0-3] JDBCExceptionReporter.logExceptions(78) | Violation
of unique constraint $$: duplicate value(s) for column(s) $$: SYS_CT_88 in statement [insert into
app_user (id, account_expired, account_locked, address, city, country, postal_code, province,
credentials_expired, email, account_enabled, first_name, last_name, password, password_hint, phone_number,
username, version, website) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
org.springframework.dao.DataIntegrityViolationException: could not insert: [edu.ksu.model.User]; nested
exception is org.hibernate.exception.ConstraintViolationException: could not insert: [edu.ksu.model.User]
at
org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:
624)
at
org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
at
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:744)
<snip/>
Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [edu.ksu.model.User]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
<snip/>
Caused by: java.sql.SQLException: Violation of unique constraint $$:
duplicate value(s) for column(s) $$: SYS_CT_88 in statement [insert into app_user (id, account_expired,
account_locked, address, city, country, postal_code, province, credentials_expired, email, account_enabled,
first_name, last_name, password, password_hint, phone_number, username, version, website) values (null, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at
org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:101)
at
org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:101)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:33)
... 143 more
Unngå både logging og kasting
Drift trenger unik feilkode for åidentifisere feilen
Utviklere trenger unik instans-ID for å identifisere feilen
Exceptions skal også testes
Bruk stubber for testing av eksterne systemer
<Stub>
Fagsystem A
<interface>
Fagsystem A
Fagsystem A
<interface>
Fagsystem A
Gjør logging enkelt
Gjør logging enkelt
Legg til kontekst der feilen oppstår
BEKK CONSULTING ASSKUR 39, VIPPETANGEN. P.O. BOX 134 SENTRUM, 0102 OSLO, NORWAY. WWW.BEKK.NO
Takk for oppmerksomheten!
trond.arve.wasskog[at]bekk.no