Sobes.tech
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 from Exception.
    • Unchecked Exceptions: Runtime errors that the compiler does not require to be explicitly handled (e.g., NullPointerException, ArrayIndexOutOfBoundsException). They inherit from RuntimeException, which in turn inherits from Exception.

Main classes in the hierarchy:

  • java.lang.Throwable
    • java.lang.Error
      • java.lang.OutOfMemoryError
      • java.lang.StackOverflowError
      • ...
    • java.lang.Exception
      • Checked Exceptions (directly from Exception)
        • java.io.IOException
        • java.lang.ClassNotFoundException
        • ...
      • java.lang.RuntimeException
        • java.lang.NullPointerException
        • java.lang.ArrayIndexOutOfBoundsException
        • java.lang.IllegalArgumentException
        • ...

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")
    }
}