java tutorial - Java -Exceptions - java programming - learn java - java basics - java for beginners
Exception in Java — represents the problem that arises during the execution of the program. In the case of an exception in Java, or an exceptional event, the normal flow of the program terminates, and the program / application terminates in an emergency mode, which is not recommended, and as such, Java cases require exception handling.
Causes of an exception
There are many reasons that may lead to the occurrence of an exception. Further, a number of similar scenarios are considered, in the context of which an exception may occur:
- The user entered invalid data.
- The file to open is not found.
- The connection to the network is lost during data transfer, or the JVM has exhausted the available memory.
Some of these exceptions are caused by a user error, others are a software error, in some cases, the cause of this may be a malfunction in material resources.
we can identify three types of exceptions. Knowing these types will allow you to later resolve problem situations related to exceptions. Below is a list of exceptions in Java with examples.
- Controlled Exceptions — A controlled exception is an exception type that occurs at the compilation stage, they are also called compile-time exceptions. The indicated exceptions should not be ignored during compilation, they require due treatment (permission) from the programmer.
For example, if you use the FileReader class in your program to read data from a file, if the file specified in the constructor does not exist, FileNotFoundException occurs, and the compiler prompts the programmer to handle this exception.
Sample Code
When you try to compile the above program, the following exceptions are displayed:
Note. Because the read () and close () methods of the FileReader class call IOException, the compiler can notify you of the IOException processing, in conjunction with FileNotFoundException.
- Uncontrolled exceptions — An uncontrolled exception is an exception that occurs at runtime. They are also called exceptions at runtime . This category can include programming errors, such as logical errors or an incorrect way of using the API. Exceptions at runtime are ignored during compilation.
For example, if you have an array of 5 elements declared in your program, an attempt to call the 6th element of the array will result in the ArrayIndexOutOfBoundsExceptionexception.
Sample Code
When compiling and executing the above program, the following exception will be received:
- Errors — are not exceptions, but represent problems that arise independently of the user or the programmer. Errors in your code are usually ignored in view of the fact that in rare cases their processing will be effective. For example, an error occurs when the stack overflows. At compile time, they are also ignored.
Hierarchy of Exceptions
- All exception classes in Java represent subtypes of class java.lang.Exception. The exception class is a subclass of the Throwable class.
- Errors represent a crash due to significant failures that are not handled by Java programs. Error generation is intended for displaying errors detected by the runtime. Examples: JVM has exhausted the available memory. Normally, programs can not repair errors caused by errors.
- The exception class is divided into two main subclasses: the IOException class and the RuntimeException class.
The link contains a list of the most common checked (checked) and unchecked built-in exceptions in Java.
Методы исключений
The following is a list of the important methods available in the Throwable class.
No. th> | Method and Description th> |
---|---|
1 | public String getMessage () Return a detailed message about the exception that occurred. The initialization of this message is done in the Throwable constructor. |
2 | public Throwable getCause () Returns the reason for the exception represented by the Throwable object. |
3 | public String toString () Returns the name of the class associated with the result of getMessage (). |
4 | public void printStackTrace () Outputting the result toString () together with the stack trace in System.err, the error output stream. |
5 | public StackTraceElement [] getStackTrace () Return an array containing each element in the stack trace. The element with the number 0 represents the top of the call stack the last element of the array displays the method at the bottom of the call stack. |
6 | public Throwable fillInStackTrace () Fills the stack trace of this Throwable object with the current stack trace, supplementing any pre-existing information in the stack trace. |
Exception handling - try and catch
The method produces exception handling when using the try and catch keywords.
Description
The try / catch block is placed at the beginning and end of the code that can throw an exception. The code in the try / catch block is a protected code, the syntax for using try / catch is as follows:
The code that is predisposed to exceptions is placed in the try block. In the case of an exception, the handling of this exception will be handled by the appropriate catch block. Each try block must immediately follow a catch block or a finally block.
- The catch statement includes an exception type declaration to be processed. If an exception occurs in the protected code, the catch block (or blocks) following the try,
- will be checked. In the event that the type of an exception occurred is represented in the catch block, the exception is passed to the catch block in the same way that the argument is passed to the method parameter.
Sample Code
Below is an array with the claimed two elements. Attempting to access the third element of the array will cause an exception to be thrown.
Output:
Multiple catch blocks
Several try blocks can follow the try block. The syntax of multiple catch blocks looks like this:
- The above statements demonstrate three catch blocks, however, after a single try, the amount of data used by the blocks can be arbitrary. If an exception occurs in the protected code, the exception is output to the first catch block in the list.
- If the data type of the generated exception is the same as ExceptionType1, it is intercepted in the specified scope. Otherwise, the exception goes to the second catch statement.
- This continues until an exception is caught or it does not pass through all the statements, in which case the current method will be terminated, and the exception will be moved to the previous method in the call stack.
Sample Code
The following is a code segment demonstrating the use of multiple try / catch statements.
Intercepting Multiple Exceptions
In a Java 7 environment, you can process more than one exception when using a single catch block, this property simplifies the code. Below is the implementation model:
Keywords throws / throw
- If the method can not handle the controlled exception, an appropriate notification is made when using the throws keyword in Java. The throws keyword appears at the end of the method signature.
- If you use the throw keyword, you can process the newly discovered exception or exception that was just intercepted.
- You must carefully distinguish the keywords throw and throws in Java, because throws is used to postpone the monitored exception, and throw, in turn, is used to call the specified exception.
- The following method displays that it generates RemoteException:
Sample Code
The method can also declare that it generates more than one exception, in which case the exceptions are represented as a list separated by commas. For example, the following method notifies you that they are generating a RemoteException and an InsufficientFundsException:
Sample Code
The finally block
- In the Java finally, you follow the try block or the catch block. The finally block in the code is always executed, regardless of the exception.
- Using the finally block allows you to run any statement intended for cleaning, no matter what happens in the protected code.
- The finally block in Java appears at the end of the catch blocks, its syntax is as follows:
Syntax
Sample Code
Output:
It should be remembered that:
- A catch statement can not exist without a try statement.
- If there is a try / catch block, the finally expression is optional.
- The try block can not exist if there is no catch or finally expression.
- The existence of any code between the try, catch, finally blocks is impossible.
Try with resources
Normally, when using different kinds of resources, such as threads, connections, etc., we have to close them directly when using the finally block. In the program presented below, we read the data from the file when using FileReader, after which it is closed by the finally block.
Sample Code
- The try-with-resources construct, also known as automatic resource management , introduces a new exception handling mechanism that was introduced in the 7th version of Java, automatically closing all resources used within the try catch block.
- To use this operator, you just need to place the specified resources in parentheses, after which the created resource will be automatically closed at the end of the block. Here is the syntax of the try-with-resources construct.
The program below reads data in a file using the try-with-resources construct.
Sample Code
When working with the try-with-resources construct, the following nuances should be taken into account:
- To use the try-with-resources construct, you must implement the AutoCloseable interface, and the corresponding close () method will be called automatically at runtime.
- You can specify one or more classes in the try-with-resources construct.
- If you specify multiple classes in the try-with-resources try block, the class data will be closed in reverse order.
- Except for parenthesizing, all elements are equal to the normal block try / catch as part of the try block.
- The resources in the try, concrete ziruyutsya to start the try block.
- The resources directly in the try block indicated as final.
Creating Your Own Exceptions
You can create your own exceptions in the Java environment. When writing your own exception classes, the following aspects should be taken into account:
- All exceptions must be children of Throwable.
- If you plan to record a controlled exception with automatic use due to a processing rule or declaration, you should extend the Exception class.
- If you want to write exceptions at runtime, you should extend the RuntimeException class.
You can define your own exception class, as shown below:
- You only need to extend the predefined Exception class to create your own exception. This category refers to controlled exceptions.
- The following InsufficientFundsException class of user-defined exceptions extends the Exception class, making it a controlled exception.
- The exception class, like all other classes, and methods.
Sample Code
To demonstrate our user-defined exceptions, the following Checking class contains the withdraw () method that generates an InsufficientFundsException.
The following program Bank demonstrates the call of the deposit () and withdraw () methods of the Checking class.
Compile all three of the above files and start the Bank. As a result, the following result will be obtained:
General exceptions
In Java, you can distinguish two categories of exceptions and errors.
- JVM exceptions - This group is represented by exceptions / errors, which are called directly and logically by the JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.
- Software exceptions - these exception data are called directly by the application or API programmers. Examples: IllegalArgumentException, IllegalStateException.