Try-Catch-Finally
Basic Syntax
Section titled “Basic Syntax”intentar { // Code that might throw an exception entero resultado = 10 / 0} capturar (excepcion e) { // Handle the error consola.mostrar_error("Error: " + e.mensaje)}With finalmente
Section titled “With finalmente”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")}Nested Try-Catch
Section titled “Nested Try-Catch”intentar { intentar { // Inner operation } capturar (excepcion inner) { lanzar "Inner error: " + inner.mensaje }} capturar (excepcion outer) { consola.mostrar_error(outer.mensaje)}Re-throwing Exceptions
Section titled “Re-throwing Exceptions”intentar { numero resultado = dividir(10, 0)} capturar (excepcion e) { consola.mostrar_advertencia("Logging error...") lanzar e.mensaje // Re-throw}Best Practices
Section titled “Best Practices”- 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