قالب وردپرس درنا توس
Home / Tips and Tricks / Attempt to capture Java: Exception handling is explained

Attempt to capture Java: Exception handling is explained



try to capture Java

Error handling – also called exception handling – is a big part of Java, but it is also one of the more divisive elements. Exception management enables a developer to anticipate problems that may occur in their code to prevent them from causing problems for users in a row. The reason this can be a nuisance is that some Java methods will actually do it force the user to handle exceptions. This is where “try to capture” in Java comes into play.

What is “try to capture” Java?

For someone who is new to programming, it can be difficult to understand why you can write code that allows an error to occur.

See also: NullPointerException in Java – Explain billion dollar errors

A good example would be FileNotFoundException. This does exactly what it says on the can: this exception is “thrown” when Java searches for a specific file and does not find it.

So, what if someone uses your app, switches to their file browser, and then deletes a save file that the app used? In that scenario, your application can understandably throw an exception. We say that this is an exception rather than a mistake because it is a problem that we can reasonably anticipate and deal with.

So you use an “try to catch” block.

In principle, try to have Java try to do something. If the operation is successful, the program continues as usual. If it is unsuccessful, then you have the option to redirect your code while noting the exception. This happens in the “catch” block.

Try capturing Java examples

Here is an example of using printing 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 of 6 entries. The highest index is therefore 5 (since “1” is at index 0). We then try to get the value from index 10.

Try running this and the message “Oops!” Will appear.

Note that we passed “Exception e” as an argument. This means that 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

Now that we have “handled” our exception, we can refer to it as a “controlled exception.”

Forced handling of exceptions

Please note that we could have written this code without handling the exception. This would cause the program to crash, but it’s our privilege!

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

So, let’s say we’re creating a small method that checks the tenth position in any list that we submit 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 well and will print “11” on the screen. But if we add the keyword “throws” 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 then forces the user to handle the exception. In fact, many Java editors automatically fill in the code with the required block. Please note that we must use the correct type of exception!

So, should you force other developers to handle exceptions when writing your own classes? It’s really up to you. Keep in mind that some scenarios really shall cause a program to quit, and forcing a developer to handle such instances only creates more pan code. In other cases, this can be a useful way to communicate potential problems to other developers and promote more efficient code.

Of course, in the example given here, there are a number of other possibilities for exceptions. What happens if, for example, someone sends a list of strings to your method? All I can say to that is, welcome to the wonderful world of Java!

This is your chance to decide what kind 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