Junior
Are you aware of the hierarchy of errors in Android?
sobes.tech AI
Answer from AI
Yes.
In Android, as in Java, the hierarchy of errors is based on the Throwable class. From it, Error and Exception are inherited.
Error: Represents serious problems that the application usually cannot recover from (e.g., JVM issues).Exception: Represents exceptional situations that can be handled by the application. They are divided into:- Checked Exceptions: Errors that the compiler requires to be handled (e.g.,
IOException). They inherit directly fromException. - Unchecked Exceptions: Runtime errors that the compiler does not require to be explicitly handled (e.g.,
NullPointerException,ArrayIndexOutOfBoundsException). They inherit fromRuntimeException, which in turn inherits fromException.
- Checked Exceptions: Errors that the compiler requires to be handled (e.g.,
Main classes in the hierarchy:
java.lang.Throwablejava.lang.Errorjava.lang.OutOfMemoryErrorjava.lang.StackOverflowError- ...
java.lang.Exception- Checked Exceptions (directly from
Exception)java.io.IOExceptionjava.lang.ClassNotFoundException- ...
java.lang.RuntimeExceptionjava.lang.NullPointerExceptionjava.lang.ArrayIndexOutOfBoundsExceptionjava.lang.IllegalArgumentException- ...
- Checked Exceptions (directly from
Example of exception handling:
// Kotlin
fun readFile(path: String) {
try {
// attempt to read the file
val fileContent = java.io.File(path).readText()
println(fileContent)
} catch (e: java.io.IOException) {
// handle input/output error
println("File read error: ${e.message}")
e.printStackTrace() // print stack trace for debugging
} catch (e: Exception) {
// handle any other exceptions if necessary
println("Another error occurred: ${e.message}")
} finally {
// this block will always execute, regardless of errors
println("File read attempt completed")
}
}