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
EasyCreate a method named divideNumbers that takes three arguments:
- A String (
num1) representing the first number - A String (
num2) representing the second number - An integer (
index) representing an array index
The method should:
- Create an array of size 2
- Store the parsed integer value of num1 divided by the parsed integer value of num2 at the given index
- Return the value at the given index
- 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 formatArithmeticException- Division by zeroArrayIndexOutOfBoundsException- 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));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap