Exceptions and Code Handling
Learn how to handle errors and exceptions in Android.
Introduction to exceptions
Every program, new or old, has an exception handling mechanism in place because exceptions will always occur. The problem is not the exceptions themselves, but how they’re handled so that we avoid crashes and unexpected events happening on the user’s end. Poor exception handling results in bad user experience.
Exception handling can control errors in the program and avoid abnormal program termination by throwing messages about the exception. This essentially means that the entire program won’t have to be terminated, and that the exception will be caught using try/catch methods.
What is an exception?
An exception is a problem that usually occurs at compile-time or runtime and presents a condition that a program can recover from, like a system crash or a null pointer exception. Exceptions are divided into two types: checked and unchecked.
Checked exceptions are logical exceptions that indicate that something is wrong with our code but that the program can recover from it. For example, if an error occurs when calling an API, we can catch it with a try/catch block at compile-time.
Unchecked exceptions (also known as runtime exceptions) usually indicate that something’s wrong with the program and that the program is unrecoverable. An example is the NullPointerException
, which is brought about by trying to ...