ComputersProgramming

Java: exceptions and their handling

Any program will work stably only if its source code is debugged, and there are no conditions that can cause unforeseen situations. The process of catching possible failures is performed at the programming stage. To do this, the developer takes into account all the expected outcomes and tries to limit the effect of the error so that it can not break the program or lead to its collapse.

When you might need to handle exceptions

In Java, exceptions can be caused by incorrect user input, lack of the resource required to run the program, or a sudden disconnection of the network. For the comfortable use of the application created by the developer, it is necessary to control the occurrence of extraordinary situations. The consumer should not wait for the hung program to complete its work, lose data as a result of unhandled exceptions or just the often appearing messages that something went wrong.

Handling Java Exceptions

What should be considered? The Java language has its built-in exception handling functionality. Of course, a large percentage of errors are caught at the compilation stage, when the system will automatically report that it can not be used any more. But there is also such kind of exceptions that arise during the program operation. The developer must be able to foresee this and design the code in such a way that it does not cause errors, but treats it in a special way or passes control to another branch.

In Java, such catching of exceptions is imposed by the compiler, so typical problems are known and have their own standard execution scheme.

Typical Exceptions

The simplest example in which you can get an exception is division. Despite all its simplicity, in expression, as a divisor, there may be zero, which will lead to an error. Well, if his appearance can be predicted earlier and prevented. But this option is not always available, so it is necessary to organize the catching exception immediately if a "division by zero" occurs.

In Java, the error handling mechanism looks like this:

  • In the heap an exception object is created, as well as any other;
  • The natural course of the program is interrupted;
  • The exception mechanism tries to find an alternative way to continue the code;
  • Finding the place of safe execution of the program in the handler, the work either will be restored, or an exception will be implemented in a special way.

The simplest example of creating an error might look like this:

If (a == null)

Throw new NullPointerException ();

Here the variable a is checked for initialization, i.e. Is not equal to the null reference. In the event that this situation occurs and special processing is needed, an exception is thrown with throw new NullPointerException ().

Some details about keywords

When working with exceptions, you often have to use Java keywords to refer to an action. There are five of them in this programming language:

  • Try. This keyword has already been encountered and means it is going to a section of code that can throw an exception. The block is limited to curly braces {}.
  • Catch. It hooks the appropriate type of exception and processes it accordingly.
  • Finally. This keyword is optional and serves to execute a piece of code that is necessary in any case, even if no exception is intercepted. It is added immediately after the try block.
  • Throw - allows you to create Java exceptions anywhere in the code.
  • Throws is a keyword that is placed in the method signature. It means that the subsequent code can throw out the Java exception of the specified type. This label serves as a signal for developers, what you need to keep in mind - the method may not work as expected.

Catch with try

The throwing in Java exception, naturally assumes that it will be treated in a special way. The most convenient way to do this is if the code section is partitioned into a block. Which possibly contains an exception. When executing such a code, the virtual machine finds an unexpected situation, understands that it is in the critical block and transfers control to the processing area.

In Java, the code is wrapped in a special try block, inside of which an exception can be thrown. Thus, several unforeseen situations are placed in it, which will be caught in one place, without creeping along the code.

The most typical code with a processing block looks like this:

Try {

// This will determine the code that can throw an exception

} Catch (Extraction_1_1 identifier_1) {

// Here the exception is processed, according to its type and conditions;

} Catch (Extraction_type_2 identifier_2) {

// Here the exception is processed, according to its type and conditions;

}

The catch keyword informs that the code subjected to the exception check should be processed as described below, provided that it matches its type. The identifier can be used inside the processing code block as arguments.

Finally

As it became clear from the previous chapter, catch blocks catch exceptions and process them. But very often there is a situation when some code should execute, regardless of whether errors were caught. For this, the finally keyword exists. It is used to increase the values of various counters, close files or connections to the network.

In this section, there are several catch blocks with invented methods of catching exceptions. For example, the code contained in try generates an unexpected situation of type Cold. Then the expressions "Caught cold!" And "Is that something to cheer about?" Will be displayed in the console. That is, the finally block is executed in any case.

In fact, there is a way to avoid running the finally. It is related to the termination of the virtual machine. Find out how this can be done on the Internet.

The throw keyword

Throw throws an exception. Its syntax looks like this:

Throw new NewException ();

Here, a new exception is created with the type NewException (). As a type, you can use classes already included in the standard Java libraries and defined earlier by the developer of your own production.

Such a construction is included in the description of any method, whose call must then occur within the try block, in order to be able to intercept it.

Keyword throws

What to do if in the development process there is a situation where the method can throw an exception, but can not handle it correctly. To do this, the method signature specifies the word throws and the type of possible exception.

This label is a kind of pointer to the client developers that the method is not capable of processing its own exception. In addition, if the error type is verifiable, the compiler will explicitly specify it.

Try with resources

In Java version 7, developers have included such an important innovation as processing the try block with resources.

Many of the objects created in Java, after their use, must be closed to save resources. Previously, you had to account for and stop such instances manually. Now they have an interface AutoClosable. It helps to automatically close already used objects, placed in the try block. Thanks to this approach, it became more convenient to write the code, its readability significantly increased.

Custom Java exception classes

The creators of the described programming language took into account many aspects when designing types of unforeseen situations. However, all variants of the outcome of events can not be prevented, therefore in Java, it is possible to determine their own exceptions that are suitable for the needs of a specific code.

The simplest way to create is to inherit from the object most appropriate to the context.

Here you inherited from Exception, a class that is used to define your own exceptions. In MyException there are two constructors - one by default, the second - with the argument of msg type String.

Then in the public class FullConstructors, the method f is implemented, the signature of which contains throws MyException. This keyword means that f can throw a Java exception of type MyException. Further, in the body of the method, text information is output to the console and the actual generation of MyException, by throw.

The second method is slightly different from the first one in that when an exception is thrown, a string parameter is passed to it, which will be reflected in the console when it is captured. In main, you see that f () and g () are placed in the try block, and the catch keyword is set to catch MyException. The result of the processing is the output of the error message to the console:

Thus, it was possible to add Java exceptions created by own hand.

Exception Architecture

Like all objects in Java, exceptions are also inherited and have a hierarchical structure. The root element of all errors thrown out in this programming language is the java.lang.Throwable class. It inherits two types - Error and Exception.

Error - notifies about critical errors and represents unchecked Java exceptions. Interception and processing of such data in most cases occurs at the development stage and does not need to be implemented in the code of the final application.

The most commonly used class for creating and analyzing exceptions is Exception. Which, in turn, is divided into several branches, including the RuntimeException. RuntimeException refers to runtime exceptions, that is, those that occur while the program is running. All classes inherited from it are unverifiable.

Common exceptions

In Java exceptions, the list of which is presented below, are used most often, so it is worth to describe each of them in more detail:

  • ArithmeticException. This includes errors related to arithmetic operations. The most striking example is the division by zero.
  • ArrayIndexOutOfBoundsException - access to the number of the element of the array that exceeds its total length.
  • ArrayStoreException - an attempt to assign an array element of an incompatible type.
  • ClassCastException is an attempt to misconstrue one type to another.
  • IllegalArgumentException - use of an invalid argument in the method call.
  • NegativeArraySizeException is an exception when creating an array of negative size.
  • NullPointerException - incorrect use of null reference.
  • NumberFormatException - occurs when the string is not converted to a number.
  • UnsupportedOperationException - the operation is not supported.

These examples are unchecked types of Java exceptions. And so look checked:

  • ClassNotFoundException - class not found.
  • IllegalAcccessException - restricting access to the class.
  • InterruptedException - interruption of the flow.
  • NoSuchFieldException - the required field does not exist.

Interpretation of exceptions

Speaking of common exceptions, it should be noted that their interpretation during development can be mistaken. Next, there is a small list explaining in more detail when an unforeseen situation may arise.

NullPointerException. The very first time that an exception occurs is to refer to an object reference that is null. This also applies to the methods of the zero instance of the class. A NullPointerException can be thrown and if the length of the array is equal to null. Avoid such situations by periodically checking objects on null.

ArrayIndexOutOfBoundsException. Any program can not exist without using arrays. Accordingly, a frequent reference to them can give rise to errors. An exception occurs when the developer tries to access an array element that is not in the index list. For example, the requested value is above the length or less than zero. It often appears as a result of the fact that the count in the array starts from zero.

conclusions

Exception handling Java is a powerful environment tool that greatly facilitates the work of the programmer and allows him to create clean and error-free code. The status and reputation of the developer company depends on how smoothly and stably the application functions.

Of course, in more or less simple programs, it's much easier to keep track of freelance situations. But in large automated complexes for several hundred thousand lines, this is possible only as a result of long-term debugging and testing.

For Java exceptions, errors that arise in some applications, individual companies offer rewards when they are enthusiasts. Especially appreciated are those that cause violation of the security policy of the software complex.

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.delachieve.com. Theme powered by WordPress.