Contents

Try Catch and Throw: Error Handling in Swift with Code Examples

Written by: David Vlijmincx

Introduction

Java's exception handling, built around try-catch blocks and throwing exceptions, provides you with tools for managing errors in your applications. Java methods can be declared to throw exceptions when problems occur, requiring calling code to either catch these exceptions with try-catch blocks or propagate them upward. This mechanism helps you prevent application crashes, improves reliability, and creates cleaner error management throughout your codebase.

Checked and Unchecked Exceptions in Java

A checked exception is a type of exception that you need to handle. These exceptions are part of the method signature as you will see in the next example. Your application won't compile of you do not handle the exception in any way.

1
2
3
public String myMethod() throws SQLException {
    throw new SQLException();
}

Unchecked exception can also be part of the signature, but you don't have to handle them. These type of exceptions extend from the RuntimeException class. That is also why they are called runtime exceptions. ArrayIndexOutOfBoundsException is an example of a Runtime exception.

Create a method that throws an exception

The easiest way to throw an exception is to use a Runtime exception like this:

1
2
3
public String myMethod() {
    throw new RuntimeException("Something unexpected has happened");
}

You don't have to specify the error in the signature and Java will simply throw this error to the code calling this method.

If you want to throw a checked exception you need to do the following:

1
2
3
4
public String myMethod() throws IndexOutOfBoundsException{
        
    throw new IndexOutOfBoundsException();
}

IndexOutOfBoundsException is a checked exception so I have to add it to the signature of the method by placing it after the throws keyword like this throws IndexOutOfBoundsException. You could also say that the method throws an Exception like this myMethod() throws Exception. This is also valid but won't let the caller know what specific exception is being thrown.

Creating you own exceptions

You can also make your own exceptions by extending from either the Exception class or the RuntimeException class depending on what type of exception you want.

To create a checked exception:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyException extends Exception {
        
    public MyException(String message) {
        super(message);
    }
}

// Use it like this
public String myMethod() throws MyException {
    throw new MyException("This happened");
}

Creating a Runtime exception is almost the same, but you extend from the RuntimeException class.

1
2
3
4
5
6
class MyRunTimeException extends RuntimeException {
        
    public MyRunTimeException(String message) {
        super(message);
    }
}

Next lets see how we can handle the exceptions that the application can throw.

Java Try catch: catching exceptions in java

Let say we want to call the following method:

1
2
3
public String myMethod() throws SQLException {
    //...
}

Because SQLException is a checked exception you need to catch or redeclare it. To catch it you will a try catch block like this:

1
2
3
4
5
try {
    main.myMethod();
} catch (SQLException e) {
    throw new RuntimeException(e);
}

When myMethod throws an exception the code will enter the catch block. Inside this block you can log that the error happened or execute other code.

You can have multiple catch clauses like this:

1
2
3
4
5
6
7
8
9
try {
    main.myMethod();
}
catch (SQLException e) {
    throw new RuntimeException(e);
}
catch (Exception e) {
    throw new RuntimeException(e);
}

In this case, if the error is of type SQLException that block will be executed. If it is not, then the block underneath the Exception will be called. The order of catch clauses is important the following won't compile:

1
2
3
4
5
6
catch (Exception e) {
    throw new RuntimeException(e);
}
catch (SQLException e) {
    throw new RuntimeException(e);
}

This won't compile because SQLException is a subtype of Exception. This makes the catch block of SQLException unreachable.

It is also possible to catch two exceptions in the same catch clause.

1
catch (SQLException | IndexOutOfBoundsException e) 

This can be handy when the code handling the exception is the same for both exceptions.

Rethrowing exceptions

It is also possible to rethrow an exception. This is often done with checked exceptions to make them runtime exceptions. This is done to prevent other code having to deal with exception handling and just letting the error bubble up.

1
2
3
4
5
6
try {
    main.myMethod();
}
catch (SQLException e) {
    throw new RuntimeException(e);
}

As you can see all you need to do is pass the exception as a parameter to RuntimeException.

Conclusion

Java's exception handling mechanism provides a way to manage errors in your applications. By using try-catch blocks, throwing appropriate exceptions, and creating custom exception types, you can build more resilient software that gracefully handles unexpected situations.

Remember these key points when working with exceptions in Java:

  1. Checked exceptions must be either caught or declared in the method signature
  2. Unchecked exceptions (RuntimeExceptions) don't require explicit handling
  3. Custom exceptions give you flexibility to create domain-specific error types
  4. The order of catch blocks matters - always catch specific exceptions first
  5. Rethrowing exceptions as RuntimeExceptions can simplify your error handling