Errors can occur during program executing. It’s a common problem for every programmer, from a beginner to a real pro. Not all errors arise through the fault of the developer. Some of them are difficult to predict, and sometimes it’s not possible. For example, while downloading a program, the network connection may suddenly drop or the power may go out. Such situations are called exceptions. Try and catch are the parts of construction used for handling exceptions in Java.

Java try and catch block

When an error occurs, Java usually stops and generates an error message. This process is called "Java throws an exception". Java provides special facilities for handling exceptions. One of them is try...catch...finally construction. Here is the syntax of try block, catch block and finally block.

//try block
try {
  // Block of code to try
}
//try catch 
catch(Exception e) {
  // Block of code to handle errors
}
finally {
 // Optional block of code 
          }
When an exception occurs in the try block, control passes to the catch block, which can handle the exception. If no such block is found, an unhandled exception message is displayed to the user and further execution of the program is stopped. It is to prevent such an emergency stop that you need to use the try..catch block. Java Try - Catch - 1

Briefly about try, catch, finally, throws keywords

Exception handling in Java is based on the use of the following keywords in a program:
  • try — defines a block of code in which an exception can occur;
  • catch — defines the block of code in which the exception is handled;
  • finally — defines a block of code that is optional, but if present, is executed anyway, regardless of the results of the try block.
These keywords are used to create special processing constructs in the program code: try catch, and try catch finally}.
  • throw — used to raise an exception;
  • throws — used in method signatures to warn that a method might throw an exception.

Easy example of Java Try Catch construction

Let's say we have a program with some array.

public class TryTest {
   public static void main(String[] args) {
       int[] myArray = new int[5];
       myArray[7] = 8;
       System.out.println(myArray[7]);
   }
}
Since we are trying to access an array element with a non-existent index, the program will exit with an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at days.TryTest.main(TryTest.java:6) Process finished with exit code 1
Let's modify this program and handle this exception with a try-catch. First comes try block, later — catch block.

//try catch example
public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (Exception myEx) {
           System.out.println("The exception was handled...");
       }

       System.out.println("This is the end of the program...");
   }
}
Now the output has changed:
The exception was handled... This is the end of the program... Process finished with exit code 0 Process finished with exit code 0
In this case, the program completed correctly, our message is displayed on the screen. The correct termination of the program is signaled by code 0 at the end of the process, while incorrect — 1. When using a try...catch block, all statements between the try and catch statements are executed first. If an exception occurs in the try block, then the normal execution order stops and proceeds to the catch statement. Therefore, when the program execution reaches the numbers[7]=8; line, the program will stop and go to the catch block In our case, we have declared the variable myEx with the type Exception. This is the base class for all exceptions, and so they can be different. For example, there are exceptions that are responsible for stack overflows, going beyond the array indexing, as in our case, pointing to Null, and so on. If we hadn't guessed with the type of exception, then the program would also have terminated incorrectly. However, we chose the Exception type for simplicity of the example, and it is the base class for all exceptions. So the catch statement (Exception myEx) will handle almost all exceptions. Handling the exception in this case After the catch block completes, the program continues its work, executing all other instructions after the catch block. If you want to see occurred exceptions, you can have the program print a stack trace of method calls. This is what the JVM does when an uncaught exception occurs: it stops the execution of the program, and prints a stack trace after executing the code of the finally block, if present.

public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (Exception myEx) {
          
         myEx.printStackTrace();
       }

       System.out.println("This is the end of the program...");
   }
}
Handling the exception in this case comes down to printing the error trace stack to the console using the printStackTrace() method defined in the Exception class.
java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at days.TryTest.main(TryTest.java:7) This is the end of the program... Process finished with exit code 0
However, the program exited correctly.

Finally! After catching

In the example and in the definitions of the key words for exception handling, we mentioned the finally block. It is optional, but if present, it will be executed regardless of the results of the try block. Let's change the exception type to NullPointerException.

public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (NullPointerException myEx) {
           System.out.println("The exception was handled...");

       }

       finally{
           System.out.println(" finally");
       }

       System.out.println("This is the end of the program...");
   }
}
Here is the output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at days.TryTest.main(TryTest.java:7) finally Process finished with exit code 1
By the way, we can specify the type of exception to be correct. Here it is IndexOutOfBoundsException.

public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (IndexOutOfBoundsException myEx) {
           System.out.println("The exception was handled...");

       }

       finally{
           System.out.println(" finally");
       }

       System.out.println("This is the end of the program...");
   }
}
In this case, the output will be as follows:
The exception was handled... finally This is the end of the program... Process finished with exit code 0
Java Try - Catch - 2

What’s the way exceptions work?

The point is that all these words —catch, throw, throws can only be used with java.lang.Throwable or its descendants. For example, you can do this:

public class MyClass {
    public static void main(String[] args) {
        try {
        } catch (Throwable thr) {
}
    }
}
However, you can't do it like this:

public class MyClass {
public static void main(String[] args) {
        try {
        } catch (String thr) {
}
    }
}

Enhancing Your Java Try-Catch Skills: FAQs to the Rescue!

Hey there, coding champ! You’ve already gotten a solid grip on the basics of try-catch blocks from the article, right? Awesome! But I bet you’re thinking, “Okay, this is cool, but when do I actually use this stuff?” Don’t worry—I’ve got your back. Let’s spice up that knowledge with some handy additions that’ll make you a try-catch pro in no time. We’re adding a shiny new FAQ section to answer your burning questions, plus a quick syntax rundown to keep things crystal clear. Ready? Let’s dive in!

FAQ: Your Try-Catch Questions, Answered!

Picture this: you’re coding away, and suddenly you hit a snag. Should you slap a try-catch block on it? Hmm, good question! I’ve gathered the most common curiosities about try-catch blocks and packed them into this FAQ section just for you. It’s like a cheat sheet for knowing when and how to wield this Java superpower. Let’s get started!

When Should I Use a Try-Catch Block?

Great question! Use a try-catch block when you suspect something might go wrong in your code—like a sneaky error that could crash your program. Think of it as your safety net. For example, if you’re reading a file and it might not exist, or dividing numbers where zero might sneak in, that’s your cue! Try-catch is perfect for handling those “uh-oh” moments gracefully, so your program keeps humming along instead of throwing a tantrum.

Do I Need Try-Catch Everywhere?

Nope, not at all! You don’t need to wrap every line of code in a try-catch—it’d be overkill, like wearing a helmet to eat cereal. Use it when you’re dealing with risky operations, like file input/output, network calls, or user input that might be wonky. If you can check for problems with an `if` statement (like making sure a number isn’t zero before dividing), do that instead. Save try-catch for the unpredictable stuff!

Can I Skip the Catch Part?

You’re catching on to everything so quickly! Yes, you can skip the catch if you pair a try with a `finally` block instead—like `try { … } finally { … }`. It’s handy when you just want to clean up resources (say, closing a file) no matter what happens. But if you’re expecting an error you need to handle, stick with the catch—it’s your best buddy for dealing with exceptions.

What’s the Deal with Multiple Catch Blocks?

Oh, you’re ready for the fancy stuff! You can stack multiple catch blocks after a try to handle different types of exceptions. Like, one for `ArithmeticException` (division by zero) and another for `NullPointerException` (oops, forgot to initialize something). It’s like having a plan for every possible hiccup—super efficient and totally doable since Java 7 even lets you catch multiple exceptions in one block with a `|` symbol. Cool, right?

How Do I Know Which Exceptions to Catch?

Don’t sweat it—it’s simpler than it sounds! Check the docs for the methods you’re using—they’ll tell you what exceptions they might throw (look for `throws` in the method signature). For example, `FileReader` might throw an `IOException`. Catch those specific ones first, and if you’re unsure, a general `Exception` catch can be your catch-all safety net. You’ll get the hang of it with practice!

A Quick Peek at Try-Catch Syntax

Okay, let’s break it down real quick—syntax time! What does a try-catch block even look like? I’ll show you the basic blueprint so you can slap it into your code like a pro. Here’s the rundown:

 try { // Your risky code goes here—like dividing by zero or opening a file int result = 10 / 0; // Uh-oh, trouble! } 
catch (Exception e) { // Handle the error here—say something nice to calm things down System.out.println("Oops, something went wrong: " + e); } 

See? Super simple! The `try` part is where you put code that might blow up, and the `catch` part swoops in to save the day if it does. You can swap `Exception` for something specific like `ArithmeticException` if you know what’s coming. Want to add a cleanup step? Toss in a `finally` block after the catch—it runs no matter what. Easy peasy!

Wrap-Up: You’ve Got This!

Wow, look at you go! With this FAQ and syntax guide, you’re ready to tackle try-catch blocks like a seasoned coder. Next time your program throws a curveball, you’ll know exactly when to whip out that try-catch magic. Keep practicing, and if you’ve got more questions, don’t be shy—drop them in the comments! You’re doing awesome, and I’m cheering you on every step of the way!