Adam E.
—In Java, you might want to explicitly throw an exception when you know your program has reached some state that would prevent it from continuing to execute successfully.
To throw an exception, we need to specify the keyword throws
along with the exception type and any additional arguments the relevant exception constructor will accept. For example, to throw a generic exception we can use the Exception
class as shown below:
public class Main { public static void main(String[] args) throws Exception { try { int x = 1 / 0; } catch (Exception exception) { throw new Exception("Something went wrong!"); } } }
This will yield the following output:
Exception in thread "main" java.lang.Exception: Something went wrong! at Main.main(Main.java:7)
Exception
ClassThe Exception
thrown above can be a bit limiting as the information provided by the exception is rather sparse. We could provide a more detailed exception message to the Exception
constructor and pass in the underlying caught exception. But there might be cases where we need more scope for custom exception attributes that are not available by using the Exception
class. Additionally, we might want to define exceptions that represent business processes not covered by the standard Java subclasses of Exception
(such as ArrayIndexOutOfBoundsException
, ArithmeticException
, and IllegalArgumentException
). We can create our own exceptions by extending the Exception
class.
Let’s say your code interfaces with some driver or third-party code. Should that third-party code experience an error, it may yield some error code. We can create a custom exception class that facilitates passing in an error code as enum
, and use this error code to perform additional actions in our application if required.
public class CustomException extends Exception { private final ErrorCode errorCode; public CustomException(String message, ErrorCode errorCode) { super(message); this.errorCode = errorCode; } public CustomException(String message, ErrorCode errorCode, Throwable cause) { super(message, cause); this.errorCode = errorCode; } public ErrorCode getCode() { return this.errorCode; } public String toString() { return super.getMessage() + " Error code: " + getCode(); } enum ErrorCode { BAD_THINGS } }
We can now throw our CustomException
:
public class Main { public static void main(String[] args) throws CustomException { try { int x = 1 / 0; } catch (Exception exception) { throw new CustomException("Something bad!", CustomException.ErrorCode.BAD_THINGS, exception); } } }
The output of this program yields:
Exception in thread "main" Something bad! Error code: BAD_THINGS at Main.main(Main.java:7) Caused by: java.lang.ArithmeticException: / by zero at Main.main(Main.java:5)
Creating custom exceptions can be helpful, but there are some general best practices to remember when deciding to implement a custom exception class:
UnsupportedOperationException
(which can be used to indicate that a request operation is not supported) and IllegalArgumentException
(which can indicate that illegal arguments have been passed to a method). These are just two of many built-in classes that extend Exception
.Exception
.Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.