Skip to content

Try-Catch-Finally

intentar {
// Code that might throw an exception
entero resultado = 10 / 0
} capturar (excepcion e) {
// Handle the error
consola.mostrar_error("Error: " + e.mensaje)
}

The finalmente block always executes, regardless of whether an exception occurred.

intentar {
texto contenido = archivo.leer("datos.txt")
consola.mostrar(contenido)
} capturar (excepcion e) {
consola.mostrar_error("Could not read file: " + e.mensaje)
} finalmente {
consola.mostrar("File operation completed")
}
intentar {
intentar {
// Inner operation
} capturar (excepcion inner) {
lanzar "Inner error: " + inner.mensaje
}
} capturar (excepcion outer) {
consola.mostrar_error(outer.mensaje)
}
intentar {
numero resultado = dividir(10, 0)
} capturar (excepcion e) {
consola.mostrar_advertencia("Logging error...")
lanzar e.mensaje // Re-throw
}
  • Catch specific exceptions when possible
  • Don’t use exceptions for normal flow control
  • Always clean up resources in finalmente
  • Log or handle exceptions meaningfully
  • Don’t catch exceptions just to ignore them