Blog |

When to Use Try-Except vs. Try-Catch

When to Use Try-Except vs. Try-Catch
Table of Contents

Are you confused when to use try-except versus try-catch? Both are popular mechanisms that gracefully handle unexpected situations. Both share a similar philosophy in syntax, where a block of code is 'tried,' and if an exception occurs, it's caught and handled in a designated way. There's one big difference between them though: try-except is for Python while try-catch is for Java.

No matter what language you're more experienced in, here are the parallels and discrepancies you need to know to master both.

How Are Try-Catch and Try-Except Blocks Similar?

Both follow a similar syntactic pattern. You encase potentially error-prone code within a try block and then the catch and except blocks define actions to handle those errors.

The syntax of the try-except block in Python is as follows:

try:
    # some code here that might raise an exception
except ExceptionType:
    # handle the exception here

In Java, the syntax for the try-catch block is as follows:

try {
    // some code here that might throw an exception
} catch (ExceptionType e) {
    // handle the exception here
}

What Are the Differences Between Try-Catch and Try-Except?

Besides the syntax difference in how you write each, there is also an additional else code block available in Python that is different.

Python

  • try: Code that might cause an exception.
  • except: Code that handles the exception.
  • else: Code that runs if the try block does not raise an exception.
  • finally: Code that always runs, whether an exception occurred or not.

Java

  • try: Code that might cause an exception.
  • catch: Code that handles the exception.
  • finally: Code that always runs, whether an exception occurred or not.

Java does not have a direct equivalent to Python's else block. The finally block in both cases is always executed regardless of whether an exception was thrown or not. Yet only in Python can you have code that runs if no exception occurs.

The else and finally blocks in both Python and Java are optional.

Let’s take a look at several examples.

Try-Except in Python

try:
  print(name)
except NameError:
  print("Variable name is not defined")
except:
  print("Something went wrong")

Output:

Variable name is not defined

Try-Except-Else-Finally in Python

def division(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Cannot divide by zero.")
        result = None
    except TypeError as e:
        print(f"Error: {e}")
        result = None
    else:
        print("Division successful.")
    finally:
        print("This part is executed irrespective of the exception")
    return result

# Test runs:
num_1 = 10
num_2 = 2
result_1 = division(num_1, num_2)
print(f"Result 1: {result_1}\n")
num_3 = 10
num_4 = 0
result_2 = division(num_3, num_4)
print(f"Result 2: {result_2}")

Output:

Division successful.
This part is executed irrespective of the exception
Result 1: 5.0

Error: Cannot divide by zero.
This part is executed irrespective of the exception
Result 2: None

In the above example, the division() function takes two arguments a and b and tries to divide number a by b . The code which might raise an exception is kept inside the try block. In this scenario, it might raise a ZeroDivisionError if b is zero or a TypeError if b is not a numeric type .

Specific exceptions are caught using the except blocks. The corresponding except block will be executed if an exception arises inside the try block, preventing the application from crashing. If there are no exceptions, the else block will run, and the finally block will always run whether an exception occurred or not.

Try-Catch-Finally in Java

public class Test {
    public static void main(String[] args)
    {

        int[] numbers = { 12, 5, 0 };

        try {
            int result = numbers[0] / numbers[1];
            System.out.println("Division successful. Result: " + result);

            // Accessing an index out of range
            System.out.println("Element at index 20: " + numbers[20]);
        }
        catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide number zero.");
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index is out of range.");
        }

        finally {
            System.out.println("This part is executed irrespective of the exception");
        }
    }
}

Output:

Division successful. Result: 2
Error: Index is out of range.
This part is executed irrespective of the exception

In the above Java code, the try block contains the code that may raise exceptions. The program attempts to divide numbers[0] by numbers[1] and also tries to access an index that is out of range, (numbers[20]) .

The catch blocks are used to catch specific exceptions that might occur in the try block. In this scenario, there are different catch blocks. One for ArithmeticException , which handles division by zero, and another for ArrayIndexOutOfBoundsException , which handles the attempt to access an index that is out of range for the array.

The finally block is used to specify code that will be executed irrespective of whether an exception occurred or not. It’s commonly used for cleanup tasks or releasing resources.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python or Java errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape