قالب وردپرس درنا توس
Home / Tips and Tricks / Try to Catch Java: Exception Handling Explained

Try to Catch Java: Exception Handling Explained



try to catch java

Error handling – also called exception handling – is a big part of Java, but it’s also one of the more controversial elements. Exception handling enables a developer to anticipate problems that may arise in their code to prevent them from causing problems for users later. The reason this can become a nuisance is because some methods actually work in Java Power the user handles exceptions. This is where “try catch” in Java comes into play.

What is “try catch” Java?

For someone new to programming, it can be difficult to understand why you might be writing code that allows a bug to occur.

See also: NullPointerException in Java – Explanation of the billion dollar bug

That would be a good example FileNotFoundException. This does exactly what it says on the tin: this exception is “thrown” when Java is looking for a specific file and cannot find it.

So what if someone uses your app, switches to their file browser, and then deletes a backup file used by the app? In this scenario, your application can understandably throw an exception. We say this is an exception rather than a bug as it is an issue that we could reasonably anticipate and handle.

So you use a “try catch” block.

Try is essentially telling Java to try to do something. If the process is successful, the program will continue as usual. If so unsuccessfulThen you have the option to redirect your code and at the same time note the exception. This is done in the “catch” block.

Try to catch a java example

Here is an example of using try catch in Java:

    try {
      int[] list = {1, 2, 3, 4, 5, 6};
      System.out.println(list[10]);
    } catch (Exception e) {
      System.out.println("Oops!");
    }

Here we create a list with 6 entries. The highest index is therefore 5 (since “1” is at index 0). We then try to get the value from index 10.

When you do this, the message “Oops!” Displayed.

Notice that we passed “exception e” as an argument. That means we can also say:

System.out.println(e);

We get the message: “java.lang.ArrayIndexOutOfBoundsException: 10”

See also: Java Beginners Course – A free and comprehensive guide to the basics of Java

After we “handle” our exception, we can refer to it as a “checked exception.”

Forced exception handling

Notice that we could have written this code without handling the exception. This would crash the program, but that is our prerogative!

In other cases, a method forces the user to handle an exception.

So let’s say we create a little method that checks the tenth position of each list we pass as an argument:

public class MyClass {

  public static void main(String[ ] args) {
      int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
      System.out.println(checkTen(list));
  }

   public static int checkTen (int[] listToCheck) {
       int outPut = listToCheck[10];
       return outPut;
   }
}

This works fine and prints “11” on the screen. However, if we add the keyword “throw” to our method signature, we can force the user to handle it.

public static int checkTen (int[] listToCheck) throws ArrayIndexOutOfBoundsException {

Now we can write our code like this:

public class MyClass {

  public static void main(String[ ] args) {
      int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   
      try {
        System.out.println(checkTen(list));
      } catch (ArrayIndexOutOfBoundsException e) {
          //System.out.println(e);
          System.out.println("Oops!");
      }    
  }

    public static int checkTen (int[] listToCheck) throws ArrayIndexOutOfBoundsException {
        int output = listToCheck[10];
        return output;
    }
}

This will force the user to deal with the exception. In fact, many Java editors automatically populate the code with the required block. Note that we need to use the right kind of exception!

Should you force other developers to handle exceptions when writing your own classes? It’s really up to you. Remember that some scenarios are real should When a program exits and a developer is forced to deal with such instances, only boilerplate code is created. In other cases, this can be a useful way to share potential problems with other developers and encourage more efficient code.

In the example given here there are of course a number of other possibilities for exceptions. For example, what if someone passes a list of strings to your method? All I can say is, welcome to the wonderful world of Java!

This is your chance to decide what type of developer you want to be! When you’re ready to find out, check out our guide to the best resources for learning Java!


Source link