Manejo de Excepciones en Java

Manejo de excepciones en Java: ArithmeticException, estructuras try-catch-finally y buenas prácticas. Descubre cómo Q2BSTUDIO ofrece software a medida, IA, ciberseguridad y soluciones cloud en AWS y Azure.

17 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Java Exception Handling

El manejo de excepciones en Java es un mecanismo esencial para gestionar errores en tiempo de ejecución y mantener el flujo normal de una aplicación. Algunos ejemplos comunes de excepciones son ClassNotFoundException, IOException, SQLException, RemoteException y ArithmeticException. Al controlar estas excepciones, los desarrolladores pueden crear aplicaciones robustas y tolerantes a fallos.

Ejemplo simple de ArithmeticException o division por cero

import java.io.*;

class Geeks {

public static void main(String[] args) {

int n = 10;

int m = 0;

int ans = n / m; // provoca ArithmeticException

// la ejecucion no llega a estas lineas si la excepcion no es manejada

}

}

Nota

Cuando ocurre una excepcion y no se maneja, el programa termina abruptamente y el codigo que sigue nunca se ejecuta.

Ejemplo con try catch finally gestionando ArithmeticException

import java.io.*;

class Geeks {

public static void main(String[] args) {

int n = 10;

int m = 0;

try {

int ans = n / m; // puede lanzar ArithmeticException

// aqui se habria impreso la respuesta si no hubiera excepcion

} catch (ArithmeticException e) {

// manejo de la excepcion: division por cero no permitida

} finally {

// el programa continua despues de manejar la excepcion

}

}

}

Salida esperada cuando se maneja la excepcion

Error Division by zero is not allowed!

Program continues after handling the exception.

Jerarquia de excepciones en Java

En Java todas las excepciones y errores son subclases de la clase Throwable. Desde ahi se bifurcan dos ramas principales

Exception

Error

Las excepciones son problemas que la aplicacion puede intentar manejar, mientras que los errores suelen estar fuera del control del programador y normalmente no se deben capturar.

Principales motivos por los que ocurren excepciones

Entrada de usuario invalida

Fallo de dispositivo

Perdida de conexion de red

Limitaciones fisicas como falta de espacio en disco

Errores en el codigo

Acceso fuera de limites

Referencia nula

Incompatibilidad de tipos

Apertura de un archivo no disponible

Errores en la base de datos

Errores aritmeticos

Ejemplos de try catch anidados

public class NestedTryExample {

public static void main(String[] args) {

try {

System.out.println(Outer try block);

try {

int a = 10 / 0; // causa ArithmeticException

} catch (ArithmeticException e) {

System.out.println(Inner catch e);

}

String str = null;

System.out.println(str.length()); // causa NullPointerException

} catch (NullPointerException e) {

System.out.println(Outer catch e);

}

}

}

Buenas practicas

Capturar excepciones concretas en lugar de interceptar excepciones generales permite una gestion mas precisa. Usar bloques finally o try con recursos para asegurar limpieza de recursos. Registrar la informacion de la excepcion y proporcionar mensajes utiles para depuracion sin exponer informacion sensible.

Como Q2BSTUDIO puede ayudar

Q2BSTUDIO es una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida, con amplia experiencia en inteligencia artificial, ciberseguridad y servicios cloud aws y azure. Nuestro equipo construye soluciones escalables y seguras que integran servicios inteligencia de negocio e implementaciones de power bi para explotar datos y generar valor. Ofrecemos proyectos de ia para empresas, desarrollo de agentes IA personalizados y consultoria en ciberseguridad para proteger activos criticos. Ademas brindamos migracion y gestion en servicios cloud aws y azure, mantenimiento y soporte para garantizar continuidad y rendimiento.

Si necesitas una aplicacion a medida o soporte para incorporar inteligencia artificial y agentes IA en tus procesos, o mejorar tus capacidades de inteligencia de negocio con power bi, Q2BSTUDIO puede diseñar e implementar la solucion adecuada, desde el analisis inicial hasta la entrega y operacion continua.

Palabras clave

aplicaciones a medida

software a medida

inteligencia artificial

ciberseguridad

servicios cloud aws y azure

servicios inteligencia de negocio

ia para empresas

agentes IA

power bi

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat