My first experience with C# exceptions, after having been a Java coder for a long time, wasn’t good. My carefully written, rigorously tested C# code suddenly started crashing. What happened? My code relied on a library written by someone else, and the owner of that library had changed a method to throw a new exception. Since my code wasn’t prepared to handle that exception, my code crashed. Had this been Java, the compiler would have alerted me to the fact that the library method is now throwing a new exception and made me update my code.
In Java, exceptions are checked by the compiler (“checked exceptions”). The compiler forces methods to declare what exceptions it can throw. It forces callers of the method to decide what to do with each possible exception. If you know how to recover from the exception, you catch the exception. If you don’t, you’re obligated to declare it using the throws keyword. Consequently, the ball gets passed to the caller of your method to deal with the exception.
“Recovering” from an exception entails gracefully handling the error to ensure the program continues to operate seamlessly. For example, if a file could not be opened because it doesn’t exist, you may want to create it. In this case you catch the FileNotFoundException exception. That’s a well-known example, so it is obvious what exception to catch. But sometimes you want to recover from application-specific errors. Maybe you want to try a customer’s backup credit card if the primary credit card is declined. Now it is not obvious what exception to catch. There may be more than one exception to catch, for example, CreditCardExpiredException, SuspiciousActivityException, CardTypeNotSupportedException and so on.