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

import java.io.File;
import java.io.FileReader;

public class Test {

   public static void main(String args[]) {		
      File f = new File("E://wikitechy/java/file.txt");
      FileReader fr = new FileReader(f); 
   }
}
click below button to copy the code. By - java tutorial - team

When you try to compile the above program, the following exceptions are displayed:

C:\>javac Test.java
Test.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
      FileReader fr = new FileReader(f);
                      ^
1 error
click below button to copy the code. By - java tutorial - team

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

public class Test {
   
   public static void main(String args[]) {
      int array[] = {1, 2, 3, 4, 5};
      System.out.println(array[7]);
   }
}
click below button to copy the code. By - java tutorial - team

When compiling and executing the above program, the following exception will be received:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
	at Test.main(Test.java:5)
click below button to copy the code. By - java tutorial - team
  • 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. Method and Description
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:

try {
   // Secure Code
}catch(NameExclusions e1) {
   // Block catch
}
click below button to copy the code. By - java tutorial - team

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.

import java.io.*;

public class Test {

   public static void main(String args[]) {
      try {
         int array[] = new int[5];
         System.out.println("Access to the third element:" + array[7]);
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("An exception:" + e);
      }
      System.out.println("Outside the block");
   }
}
click below button to copy the code. By - java tutorial - team

Output:

An exception:java.lang.ArrayIndexOutOfBoundsException: 7
Outside the block
click below button to copy the code. By - java tutorial - team

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.

try {
   file = new FileInputStream(fileName);
   x = (byte) file.read();
}catch(IOException e1) {
   e1.printStackTrace();
   return -1;
}catch(FileNotFoundException e2) // Invalid! {
   e2.printStackTrace();
   return -1;
}
click below button to copy the code. By - java tutorial - team

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:

catch (IOException|FileNotFoundException ex) {
   logger.log(ex);
   throw ex;
click below button to copy the code. By - java tutorial - team

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

import java.rmi.RemoteException;
public class Test {

   public void deposit(double amount) throws RemoteException {
      // Implementation of the method
      throw new RemoteException();
   }
   // The remainder of the class definition
}
click below button to copy the code. By - java tutorial - team

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

import java.rmi.RemoteException;
public class Test {

   public void withdraw(double amount) throws RemoteException, 
      InsufficientFundsException {
      // Implementation of the method
   }
   // The remainder of the class definition
}
click below button to copy the code. By - java tutorial - team

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

try {
   //Secure Code
}catch( ExceptionType1 e1) {
   // Block catch
}catch( ExceptionType2 e2) {
   // Block catch
}catch( ExceptionType3 e3) {
   // Block catch
}finally {
   // The finally block is always executed.
}
click below button to copy the code. By - java tutorial - team

Sample Code

public class Test {

   public static void main(String args[]) {
      int array[] = new int[2];
      try {
         System.out.println("Access to the third element:" + array[3]);
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("An exception:" + e);
      }finally {
         array[0] = 6;
         System.out.println("The value of the first element: " + array[0]);
         System.out.println("The finally statement is executed.");
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output:

An exception:java.lang.ArrayIndexOutOfBoundsException: 3
The value of the first element: 6
The finally statement is executed.

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

import java.io.FileReader;
import java.io.File;
import java.io.IOException;

public class Test {

   public static void main(String args[]) {
      FileReader fr = null;		
      try {
         File f = new File("file.txt");
         fr = new FileReader(f); 
         char [] array = new char[10];
         fr.read(array);   // Reading the contents of an array
         for(char c : array)
         System.out.print(c);   // display characters on the screen, one by one
      }catch(IOException e1) {
         e1.printStackTrace();
      }finally {
         try {
            fr.close();
         }catch(IOException e2) {		
            e2.printStackTrace();
         }
      }
   }
}
click below button to copy the code. By - java tutorial - team
  • 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.
try(FileReader fr = new FileReader("
The path to the file")) {
   // resource use
   }catch() {
      // body catch
   }
}
click below button to copy the code. By - java tutorial - team

The program below reads data in a file using the try-with-resources construct.

Sample Code

import java.io.FileReader;
import java.io.IOException;

public class Test {

   public static void main(String args[]) {
      try(FileReader fr = new FileReader("E://Soft/NetBeans 8.2/Projects/test/test/file.txt")) {
         char [] array = new char[10];
         fr.read(array);   // Reading the contents of an array
         for(char c : array)
         System.out.print(c);   // display characters on the screen, one by one
      }catch(IOException e) {
         e.printStackTrace();
      }
   }
}
click below button to copy the code. By - java tutorial - team

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:

class MyException extends Exception {
}
click below button to copy the code. By - java tutorial - team
  • 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

// File name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception {
   private double amount;
   
   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }
   
   public double getAmount() {
      return amount;
   }
}
click below button to copy the code. By - java tutorial - team

To demonstrate our user-defined exceptions, the following Checking class contains the withdraw () method that generates an InsufficientFundsException.

// File name Checking.java
import java.io.*;

public class Checking {
   private int number;
   private double balance;
   
   public Checking(int number) {
      this.number = number;
   }
   
   public void deposit(double amount) {
      balance += amount;
   }
   
   public void withdraw(double amount) throws InsufficientFundsException {
      if(amount <= balance) {
         balance -= amount;
      }else {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   
   public double getBalance() {
      return balance;
   }
   
   public int getNumber() {
      return number;
   }
}
click below button to copy the code. By - java tutorial - team

The following program Bank demonstrates the call of the deposit () and withdraw () methods of the Checking class.

// 
File name Bank.java
public class Bank {

   public static void main(String [] args) {
      Checking c = new Checking(101);
      System.out.println("Deposit $300...");
      c.deposit(300.00);
      
      try {
         System.out.println("\nRemove $100...");
         c.withdraw(100.00);
         System.out.println("\nRemove $400...");
         c.withdraw(400.00);
      }catch(InsufficientFundsException e) {
         System.out.println("Sorry, but you have $" + e.getAmount());
         e.printStackTrace();
      }
   }
}
click below button to copy the code. By - java tutorial - team

Compile all three of the above files and start the Bank. As a result, the following result will be obtained:

Deposit $300...
Withdrawal $100...
Withdrawal $400...
Sorry, but you $200.0
InsufficientFundsException
         at Checking.withdraw(Checking.java:25)
         at Bank.main(Bank.java:13)

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.

Related Searches to Java - Exceptions