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 cannot disrupt the program or lead to its crash.
When Exception Handling May Be Required
In Java, exceptions can be caused as a result of incorrect user input, the lack of a resource necessary for the program to work, or a sudden network outage. For comfortable use of the application created by the developer, it is necessary to control the emergence of emergency situations. The consumer should not wait for the hang-up program to finish, lose data as a result of unhandled exceptions or just frequent messages that something went wrong.
Java exception handling
What to consider? The Java language has its own built-in exception handling functionality. Of course, a large percentage of errors are caught even at the compilation stage, when the system automatically reports that it is impossible to use it further. But there is also the kind of exception that occurs during program operation. The developer must be able to anticipate this and design the code so that it does not cause an error, but processes it in a special way or transfers control to another branch.
In Java, such a 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 where an exception can be thrown is division. Despite all its simplicity, in the expression, as a divisor, it may turn out to be zero, which will lead to an error. It is good if its appearance can be predicted earlier and prevented. But this option is not always available, therefore, catching an exception must be organized directly when a "division by zero" occurs.
In Java, the error handling mechanism looks like this:
- an exception object is created on the heap, just like any other;
- the natural course of the program is interrupted;
- an 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 will either be restored, or the 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. whether the reference to the object is null. In the event that such a situation arose and special handling is needed, an exception is thrown using throw new NullPointerException ().
Some Keyword Details
When working with exceptions, you often have to use Java keywords to indicate an action. There are five of them in this programming language:
- Try it. This keyword has already been encountered, and it means a transition to a section of code that can throw an exception. The block is limited to curly braces {}.
- Catch. It intercepts the desired type of exception and processes it accordingly.
- Finally. This keyword is optional and serves to execute a certain section of code that is necessary in any case, even if no exceptions are caught. It is added immediately after the try block.
- Throw - allows you to create Java exceptions anywhere in your code.
- Throws is a keyword that is put in the method signature. It means that subsequent code may throw a Java exception of the specified type. Such a label serves as a signal for developers to keep in mind - the method may not work as expected.
Catch with try
Throwing an exception in Java naturally implies that it will be handled in a special way. This is most conveniently done if the code section is fenced off in a certain block. Which possibly contains an exception. When such code is executed, the virtual machine will find an unforeseen situation, understand that it is in a critical block and transfer control to the processing section.
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 at once, which will be caught in one place without spreading over the code.
The most typical code with a processing unit looks like this:
try {
// Code will be defined here that can throw an exception
} catch (Exception_type_1 identifier_1) {
// Here the exception is processed according to its type and conditions;
} catch (Exception_Type2 ID_2) {
// Here the exception is processed according to its type and conditions;
}
The catch keyword indicates that the code that has been checked for exception must 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 a situation arises when some code should be executed regardless of whether errors were caught. There is a finally keyword for this. It is used to increase the values of various counters, close files or network connections.
This section presents several catch blocks with invented methods for catching exceptions. For example, the code contained in try generates an unexpected situation like Cold. Then the expression “Caught cold!” Will be displayed in the console and "Is that something to cheer about?". That is, the finally block is executed anyway.
Actually, there is a way to avoid running finally. It is associated with the shutdown of the virtual machine. You can find how to implement this on the Internet.
Throw keyword
Throw throws an exception. Its syntax looks like this:
throw new NewException ();
This creates a new exception of type NewException (). As a type, classes already included in the standard Java libraries and previously defined by the developer of their own production can be used.
Such a construction is included in the description of a method, which then must be called within the framework of the try block in order to be able to intercept it.
Keyword throws
What to do if during the development process a situation arises when a method can throw an exception, but is not able to handle it correctly. For this, the word throws and the type of possible exception are indicated in the method signature.
This label is a kind of pointer for client developers that the method is not able to handle its own exception. Moreover, if the type of error is verifiable, then the compiler will force it to indicate this explicitly.
Try with resources
In Java version 7, developers included such an important innovation as processing a try block with resources.
Many created objects in Java, after their use should be closed to save resources. Previously, I had to take this into account and stop such instances manually. Now they have the AutoClosable interface. It helps to automatically close already used objects placed in the try block. Thanks to this approach, writing code has become more convenient, and its readability has increased significantly.
Native Java Exclusion Classes
The creators of the described programming language took into account many aspects when designing types of unforeseen situations. However, it is impossible to prevent all variants of the outcome of the events, therefore, Java has the ability to define its own exceptions that are suitable specifically for the needs of a particular code.
The easiest way to create is to inherit from the object that is most suitable for the context.
This is where inheritance from Exception occurred, a class that is used to define its own exceptions. There are two constructors in MyException - one by default, the second with an msg argument of type String.
Then, in the public FullConstructors class, the f method 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 MyException generation is thrown by throw.
The second method is slightly different from the first in that when you create an exception, a string parameter is passed to it, which will be reflected in the console when it is caught. In main, you can 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 will be an error message output to the console:
Thus it turned out to add Java exceptions created by hand.
Exception Architecture
Like all objects in Java, exceptions are also inherited and have a hierarchical structure. The root element of all errors thrown in this programming language is the java.lang.Throwable class. Two types are inherited from it - Error and Exception.
Error - Alerts you to critical errors and represents unchecked Java exceptions. The interception and processing of such data in most cases occurs at the development stage and does not need to be implemented in the final application code.
The most commonly used class for creating and analyzing exceptions is Exception. Which, in turn, is divided into several branches, including RuntimeException. RuntimeException includes runtime exceptions, that is, occurring while the program is running. All classes inherited from it are unchecked.
Common Exceptions
In Java, exceptions, the list of which is presented below, are used most often, therefore it is worth describing each of them in more detail:
- ArithmeticException. This includes errors related to arithmetic operations. The most striking example is division by zero.
- ArrayIndexOutOfBoundsException - access to the number of an array element that exceeds its total length.
- ArrayStoreException - An attempt to assign an array element of an incompatible type.
- ClassCastException - an attempt to cast one type to another incorrectly.
- IllegalArgumentException - using an invalid argument in a method call.
- NegativeArraySizeException - exception when creating an array of negative size.
- NullPointerException - misuse of a null reference.
- NumberFormatException - occurs when a string is converted to a number incorrectly.
- UnsupportedOperationException - operation is not supported.
These examples are unchecked Java exception types. And here is what the verifiables look like:
- ClassNotFoundException - the class was not detected.
- IllegalAcccessException - class access restriction.
- InterruptedException - interruption of the thread.
- NoSuchFieldException - The required field does not exist.
Interpretation of exceptions
Speaking about frequently encountered exceptions, it should be noted that their interpretation during development may be perceived incorrectly. Next is a short list explaining in more detail when an unforeseen situation may arise.
NullPointerException. The very first case when an exception occurs is a reference to an object reference that is null. This also applies to methods of a null instance of a class. A nullPointerException can also be thrown if the array is null. Periodic checking of objects for null will help to avoid such situations.
ArrayIndexOutOfBoundsException. Any program cannot exist without the use of arrays. Accordingly, frequent access to them can cause errors. An exception occurs when a developer tries to access an array element that is not in the index list. For example, the requested value is greater than length or less than zero. It often appears as a result of the fact that the count in the array starts from zero.
conclusions
Java Exception Handling is a powerful environment tool that makes the programmer’s job much easier and allows him to create clean and error-free code. The status and reputation of the development company depends on how smoothly and stably the application functions.
Of course, in more or less simple programs, tracking abnormal situations is much easier. But in large automated complexes with several hundred thousand lines, this is possible only as a result of lengthy debugging and testing.
For Java exceptions, errors from which arise in some applications, some companies offer rewards when they are found by enthusiasts. Those that cause a violation of the security policy of the software package are especially appreciated.