Menu
Coddy logo textTech

Try-Catch Basics

Part of the Logic & Flow section of Coddy's Java journey — lesson 40 of 59.

Try-catch blocks in Java are used to handle exceptions (errors) that might occur during program execution. The code that might throw an exception goes in the try block, and the error handling code goes in the catch block.

Here's the basic structure of a try-catch block:

try {
   // Code that might throw an exception
} catch (ExceptionType e) {
   // Code to handle the exception
}

Let's see it in action with Integer.parseInt(), which converts a String to an integer:

String text = "abc";
try {
   int number = Integer.parseInt(text);
   System.out.println(number);
} catch (NumberFormatException e) {
   System.out.println("Error: Not a valid number");
}

After executing the above code, the output is:

Error: Not a valid number

challenge icon

Challenge

Easy

Create a method named divideNumbers that takes three arguments:

  1. A String (num1) representing the first number
  2. A String (num2) representing the second number
  3. An integer (index) representing an array index

The method should:

  1. Create an array of size 2
  2. Store the parsed integer value of num1 divided by the parsed integer value of num2 at the given index
  3. Return the value at the given index
  4. Handle all possible exceptions with appropriate error messages

Return messages should be:

  • For NumberFormatException: "Error: Invalid number format"
  • For ArithmeticException: "Error: Division by zero"
  • For ArrayIndexOutOfBoundsException: "Error: Invalid array index"
  • For successful operation: return the result as a string

Cheat sheet

Try-catch blocks handle exceptions (errors) that might occur during program execution. Code that might throw an exception goes in the try block, and error handling code goes in the catch block.

Basic structure:

try {
   // Code that might throw an exception
} catch (ExceptionType e) {
   // Code to handle the exception
}

Example with Integer.parseInt():

String text = "abc";
try {
   int number = Integer.parseInt(text);
   System.out.println(number);
} catch (NumberFormatException e) {
   System.out.println("Error: Not a valid number");
}

Common exception types:

  • NumberFormatException - Invalid number format
  • ArithmeticException - Division by zero
  • ArrayIndexOutOfBoundsException - Invalid array index

Try it yourself

import java.util.Scanner;

public class Main {
    public static String divideNumbers(String num1, String num2, int index) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String num1 = scanner.nextLine();
        String num2 = scanner.nextLine();
        int index = Integer.parseInt(scanner.nextLine());
        
        System.out.println(divideNumbers(num1, num2, index));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow