Table of Contents
Exceptions are interruptions in the normal flow of program thanks to an error and other exceptional issue. If you don't handle it properly, it can cause your entire program to terminate and output an error.
Examples of when exceptions can occur:
- when a divide by zero operation was attempted
- a network connection being interrupted
- a user entering incorrect data
In this lesson, we'll learn how to safely and gracefully handle an exception so that your program can continue running properly.
We're trying to prevent this from happening.
Try Catch block
Exceptions in Java are handled using the try-catch
block. The try
block is where the code that could throw an exception is run, whereas the catch
block is the code that you want to run if an exception is indeed thrown.
This is the format for catching exceptions:
JAVAtry {
// code to try
} catch(Exception e) {
// code to handle exception
}
Now let's look at a basic example:
JAVApublic class Main {
public static void main(String[] args) {
try {
int test = 1 / 0;
} catch(ArithmeticException e) {
System.out.println(e);
}
}
}
BASHjava.lang.ArithmeticException: / by zero
Finally block
When you want to run code no matter if an exception was thrown or not, you can use the finally
block:
JAVApublic class Main {
public static void main(String[] args) {
try {
int test = 1 / 0;
} catch(ArithmeticException e) {
System.out.println("An ArithmeticException was thrown!");
} finally {
System.out.println("Moving on!");
}
}
}
BASHAn ArithmeticException was thrown!
Moving on!
Multiple Exceptions
You can handle multiple exceptions by chaining the catch
blocks:
JAVApublic class Main {
public static void main(String[] args) {
try {
String str = null;
str.length();
} catch(ArithmeticException e) {
System.out.println("An ArithmeticException was thrown!");
} catch(NullPointerException e) {
System.out.println("A NullPointerException was thrown!");
} finally {
System.out.println("Moving on!");
}
}
}
BASHA NullPointerException was thrown!
Moving on!
In the above code, we have defined multiple catch
blocks and the correct one was ran when that exception was thrown.
Throwing an Exception
You can throw an exception by using the throw
keyword:
JAVApublic class Main {
public static void main(String[] args) {
try {
throw new NullPointerException("NULL");
} catch(NullPointerException e) {
System.out.println("A NullPointerException was thrown!");
} finally {
System.out.println("Moving on!");
}
}
}
BASHA NullPointerException was thrown!
Moving on!
We can throw our own exceptions! Now if you're wondering why this is useful, well, you can use exceptions to ensure that things in your program are progressing correctly, like this:
JAVApublic class Main {
static void checkMoney(int money) {
if (money < 200) {
throw new ArithmeticException("You must have at least $200.");
} else {
System.out.println("You have enough money!");
}
}
public static void main(String[] args) {
int money = 100;
checkMoney(money);
}
}
BASHException in thread "main" java.lang.ArithmeticException: You must have at least $200.
at Main.checkMoney(Main.java:5)
at Main.main(Main.java:14)
Now that the method checkMoney
can throw an exception of its own, you can choose to handle it like any other risky piece of code:
JAVApublic class Main {
static void checkMoney(int money) {
if (money < 200) {
throw new ArithmeticException("You must have at least $200.");
} else {
System.out.println("You have enough money!");
}
}
public static void main(String[] args) {
int money = 100;
try {
checkMoney(money);
} catch(ArithmeticException e) {
System.out.println("You must have at least $200.");
}
}
}
BASHYou must have at least $200.
Not only is that a much cleaner output, but you can fully control it entirely, and even run more code if needed.
- Getting Started with TypeScript
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API