Exceptions and Generics
Handle failure properly with exceptions, and write code that works for any type with generics and type erasure.
- Module 5 of 11
- Intermediate
- 10 chapters
- 47 min
Real programs fail, and good ones fail clearly. Generics let one piece of code work for any type safely — you will use both on nearly every page of Java.
What you will be able to do
- Handle errors with try, catch, finally and try-with-resources
- Choose between checked and unchecked exceptions
- Write generic classes and methods with bounds
- Explain type erasure and when to use wildcards
Chapters
1. What an Exception IsAn exception is an object describing an error, which interrupts normal execution.5 min2. try, catch, finallyA catch block handles exceptions of its type and all its subclasses (polymorphism, 03javaoop.md Ch 4).3 min3. The Hierarchy: Checked vs UncheckedError — serious JVM problems: out of memory (02operatingsystems.md Ch 5), stack overflow (02operatingsystems.md Ch 6). Don't4 min4. try-with-resourcesA resource is anything that must be closed when you're done: files, network sockets, database connections. Each holds an operating3 min5. Your Own Exceptions, and Good PracticeA custom exception is a class that extends Exception (checked) or RuntimeException (unchecked), carrying a clear name and any extra4 min6. Why Generics ExistA warehouse with unlabelled boxes. Anyone can put anything in any box. When you open the box you expected to contain shoes, you find a2 min7. Generic Classes and MethodsA generic class declares type parameters in angle brackets: class Box<T>. T is a placeholder filled in when the class is used.3 min8. Bounded Types"Box of — must be something that can be measured." You can fill the blank with apples or bananas, not with "happiness".2 min9. Type ErasureThe "SHOES ONLY" labels are checked at the warehouse door — and then peeled off. Inside the warehouse, every box looks the same. The4 min10. Wildcards and PECSGenerics are invariant: List<Integer> is not a List<Number>, even though Integer is a Number:4 min
Extras
The Whole StoryThe whole module retold as one story — no new facts, a fast revision of Exceptions and Generics.RevisionInterview QuestionsReal interview questions on Exceptions and Generics, answered the way you would say them out loud.Interview prepQuick ReferenceGlossary and cheat sheet for Exceptions and Generics — the page to reread before an interview.Reference