This content originally appeared on DEV Community and was authored by angelperez0709
One of the first things you study when you study programming is exception handling, which is fundamental to develop applications efficiently and avoid unexpected situations.
But first, what is an exception? Exceptions are errors that happen due to errors in programming or not related to it, for example, trying to read a file that does not exist, a connection failure with the server or trying to divide by 0.
What kind of exceptions are there?
In Java (and similarly in other languages), exceptions are divided into two major groups: checked and unchecked.
- Checked Exceptions
These are exceptions that the compiler forces you to handle, either with a try/catch block or by declaring the exception with throws. They represent recoverable and expected situations during execution, such as problems when accessing files or networks.
FileReader reader = new FileReader("file.txt"); // May throw FileNotFoundException
- Unchecked Exceptions
These exceptions you are not obliged to handle explicitly, although you should do so if you don't want your application to fail unexpectedly. For example accessing non-existing positions in an empty array or inserting an incorrect type into an array.
List<String> lista = null;
lista.get(0); // Lanza NullPointerException
Object[] array = new String[3];
array[0] = new Integer(3);
What happens if we don't handle exceptions?
In one of the first applications I programmed, I wanted to add two numbers entered by console. My code looked like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type a number:");
int firstNumber = Integer.parseInt(scanner.nextLine());
System.out.println("Type another number:");
int secondNumber = Integer.parseInt(scanner.nextLine());
System.out.printf("The sum is: %d%n", firstNumber + secondNumber);
}
El resultado esperado hubiera sido ver la suma de 2 números como 2 + 3 = 5, pero ¿qué pasa si en vez de un número introduzco la palabra three?.
Mi increíble aplicación lanzará lo siguiente:
Exception in thread "main" java.lang.NumberFormatException: For input string: "three"
In case a user would have entered the word "three" the program would have stopped and the user would not have understood what happened.
How do we handle an exception?
To handle exceptions we have the try...catch block.
- The try block contains the code that could throw an exception.
- The catch block catches the thrown exception and allows you to handle it in a controlled way. You can catch as many exceptions as you need, depending on the possible bugs you want to handle. Using my previous corrected code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Type a number:");
int firstNumber = Integer.parseInt(scanner.nextLine());
System.out.println("Type another number:");
int secondNumber = Integer.parseInt(scanner.nextLine());
System.out.printf("The sum is: %d%n", firstNumber + secondNumber);
} catch (NumberFormatException e) {
System.err.println("You must type numbers.");
} catch (ArithmeticException e) {
System.err.println("An arithmetic error occurred: " + e.getMessage());
}
}
Now the user will know why the application has failed and will be able to write the numbers correctly.
Another way to handle exceptions is to delegate their handling with the throws clause. This tells the compiler (and the programmer calling the method) that an exception can be thrown from that method.
This approach is useful when you want to centralize error handling and avoid duplicating try...catch blocks in each method.
//Customized exception
class InvalidOperationException extends Exception{
public InvalidOperationException(String message){
super(mensaje);
}
}
//Class with methods that throws exceptions
class Calculator{
public function square(double a) throws InvalidOperationException{
if(a < 0){
throw new InvalidOperationException("The square root of a negative number does not exist");
}
return Math.sqrt(a)
}
public function divide(double a,double b) throws InvalidOperationException{
if(b == 0){
throw new InvalidOperationException("You can't divide by zero");
}
return a/b;
}
}
// Principal class
public class AppCalculator{
Calculator calculator = new Calculator();
public static void main(String[] args){
System.out.println("Square root: "+calculator.square(4));
System.out.println("Divide: "+calculator.divide(15,4));
System.out.println("Square root: "+calculator.square(-10));//Error
System.out.println("Divide: "+calculator.divide(123,0));//Error, pero no se ejecutará porque entra en la sentencia catch
try{
}catch(InvalidOperationException e){
System.err.println("Error en la operación: "+ e.getMessage());
}
}
If you want to become a great software engineer, learning how to handle errors properly is not optional — it's essential.
So next time something goes wrong in your code — don’t panic. Handle it 😉
This content originally appeared on DEV Community and was authored by angelperez0709

angelperez0709 | Sciencx (2025-06-16T14:30:39+00:00) Why Proper Exception Handling Matters More Than You Think. Retrieved from https://www.scien.cx/2025/06/16/why-proper-exception-handling-matters-more-than-you-think/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.