×

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular logic of the instructions and abruptly ends the process.

Luckily, with a little planning and coding, you can frequently handle these exceptions graciously, enabling your code to keep operating and giving you information for identifying the reason for the unexpected outcome.

How the exceptions are handed

A class or function that encounters an exception generates the exception object and passes the data to that same runtime system (JVM).

The call stack is then traversed by the runtime system to ascertain which layer can manage an exception that was raised or thrown. The search starts with the method where exception was created and proceeds step-by-step through all the call stacks until an exception handler is located. It detects a match when the exception's type matches one that the exception handler can handle.

List of java exceptions with examples

Java defines exception kinds that are connected to its different class libraries. Java also gives users the option to create custom exceptions.

Java exception list

The Built-in Exceptions:

The built-in exceptions are the exceptions that exist in Java libraries. These exceptions can be used to explain a few different fault scenarios. The list of significant built-in Java exceptions is shown below.

  1. ArithmeticException: It is thrown whenever an exceptional circumstance occurs during an arithmetic operation.
  2. ArrayIndexOutOfBoundsException: It must be thrown to let the user know that an array was accessed using an improper index. Its index is either greater or equal to the array size, or it is negative.
  3. ClassNotFoundException: The classNotFoundException in Java arises when the JVM (Java Virtual Machine) tries to load a specific class but can't find the desired class in the classpath you gave, as the name implies. Your classpath is broken as a result of this (which is be a very common problem in the Java world). Beginners in Java may find this issue particularly perplexing. It must be caught or thrown to the caller because ClassNotFoundException is indeed a checked exception.
  4. FileNotFoundException: The java.io package also contains the exception class known as FileNotFoundException. The problem arises when we attempt to access a file that isn't installed on the system. It arises at run time rather than compile time, making it a checked exception.
  5. IOException: When performing input or output actions, such as reading a file or accessing a file, an IOException, or input-output exception, may arise. For instance, if we attempt to read a file using the incorrect path, we receive a FileNotFound Exception. Under the heading of the checked Exceptions, the IOExceptions fall. Exceptions that occur during the compilation of a Java programme are those that have been checked. FileNotFoundException, SSLException, and other subclasses of IOException are only a few examples.
  6. InterruptedException: The execution of any thread that is dozing off or waiting for anything can be interrupted by calling the interrupt() method, which displays an InterruptedException message. The interrupt() function of the Thread class can be used to stop a thread that would be dozing off or waiting.
  7. NoSuchFieldException: When the requested field (or variable) is missing from a class, it is thrown.
  8. NoSuchMethodException: When attempting to access a method that cannot be found, it is thrown.
  9. NullPointerException: Referencing the elements of a null objects causes an exception to be triggered. Null is a symbol for nothing.
  10. NumberFormatException: When a method tries to convert a string to a numeric representation but fails, this exception is thrown.
  11. RuntimeException: This shows an exception that happens in real time.
  12. StringIndexOutOfBoundsException: It is thrown by methods of the String class when such a value seems to be either negative or larger than the length of the string.
  13. IllegalArgumentException: When the method cannot be reached by the programme for a specific operation, an exception that would produce an error or error message. The unchecked exception applies to it.

Illustrations of the Built-in Exception

  • Arithmetic exception
// The ArithmeticException in Java application
class ArithmeticException _Sahithi 
{
    public static void main(String args[])
    {
        try {
            int s = 40, h = 0;
            int r = s/h;  // it cannot be divide by the zero
            System.out.println ("Answer = " + r);
        }
        catch(ArithmeticException e) {
            System.out.println (" it is a number tha cannot be divided by 0 ");
        }
    }
}

Output:

Java exception list
  • NullPointer Exception
// NullPointerException example programme in Java 
class NullPointer_Sahithi
{
    public static void main(String args[])
    {
        try {
            String  h= null; //the value that is null
            System.out.println(h.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException");
        }
    }
}

OUTPUT:

Java exception list
  • StringIndexOutOfBound Exception
// An example StringIndexOutOfBoundsException Java programme
class StringIndexOutOfBound_Sahithi
{
    public static void main(String args[])
    {
        try {
            String h = "The way she is smiling is very attractive "; // length is 42
            char s = h.charAt(44); // here we are accessing the 45th element
            System.out.println(s);
        }
        catch(StringIndexOutOfBoundsException e) {
            System.out.println("…StringIndexOutOfBoundsException…");
        }
    }
}

Output :

Java exception list
  • FileNotFound Exception
// Java example programme for the FileNotFoundException exception
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
 class Sahithi {
 
    public static void main(String args[])  {
        try {
 
            // the file which is in the following does not exist
            File file = new File("E://file.txt");
 
            FileReader sr = new FileReader(file);
        } catch (FileNotFoundException e) {
           System.out.println("No such file exists");
        }
    }
}

Output:

Java exception list
  • IllegalArgumentException: The eligibility of a person to vote is determined by this programme. There won't be any errors thrown if the age is above or equal to 18. An error with an error statement will be generated if the aged is less than 18.

Additionally, "throw new IllegalArgumentException()" can be specified without an error message. In the IllegalArgumentException() function, we may optionally specify Integer.toString(variable name), which will print the name of the argument that does not meet the specified criterion.

/*whatever may be the package// exclude the package name from this text */
 
import java.io.*;
 
class Sahithi {
   public static void print(int a)
    {
         if(s>=18){
          System.out.println("Voting Rights Eligible");
          }
          else{
    
          throw new IllegalArgumentException("Unqualified to Vote");                        
          }
    }
    public static void main(String[] args) {
         Kamal.print(15);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Unqualified to Vote at Kamal.print(File.java:14)
at Kamal.main(File.java:20)

The user defined exceptions

Java's built-in exceptions may occasionally be unable to adequately explain a particular circumstance. In certain circumstances, the user may also produce what are known as "user-defined Exceptions."

The steps for creating a user-defined exception are as follows.

  • An exception class that is a subclasses of an Exception that class should be created by the user. Given that every exception is a subclass of an Exception that subclass, the user should do the same for his class. This is accomplished as follows:
class OwnException extends Exception
  • It is possible to create a default constructor for the exception class.
OwnException(){}
  • Another option is to create a constructor with parameters that takes a string.

This can be used to store exception information. We can use this to call the superclass(Exception) constructor and pass the string along.

OwnException(String sr)
{
   super(sr);
}
  • It is necessary to generate an object that belongs to the user-defined exception class and toss it through the throw clause in order to invoke an exception of that type, as in:
OwnException sr = new OwnException(“details of the exception”);
throw sr;
  • How to construct your own exception class, MyException, as demonstrated in the application below.
  • Three arrays are used to store information about account numbers, client names, and balance amounts.
  • A for-loop is used in the main() method to display the details. At this point, it is checked to see if the balance in any account falls below the required minimum balance.
  • If this is the case, then "Balance amount is less" is displayed and MyException is raised.

Let us have a look at to the following example

// Programming in Java to display a user-defined exception
 
// When balance is violated, this software throws an exception.
// the below given amount is Rs 20000
class OwnException extends Exception
{
    //account information is stored
    private static int acc[] = {2002, 2003, 2004, 2005};
 
    private static String iden[] =
                 {"Hymavathi", "Janardhan", "Swetha", "Archana", "Sahithi"};
 
    private static double mon[] =
         {20000.00, 22000.00, 3600.0, 899.00, 4100.55};
 
    // it is the default constructor
    OwnException() {    }
 
    // it is the parameterized constructor
    OwnException(String sr) { super(sr); }
 
    // the main() is written here
    public static void main(String[] args)
    {
        try  {
            // display the table's heading
            System.out.println("ACC" + "\t" + "CUST" +
                                           "\t" + "MON");
 
            // show the exact account details
            for (int k = 0; k < 5 ; k++)
            {
                System.out.println(acc[k] + "\t" + iden[k] +
                                               "\t" + mon[k]);
 
                // show your own exception in case of balance < 20000
                if (mon[k] < 20000)
                {
                    OwnException sh =
                       New OwnException("Balance falls short of 20000");
                    throw sh;
                }
            }
        } //it is the end of try
 
        catch (OwnException e) {
            e.printStackTrace();
        }
    }
}

Here the runtime error is

OwnException: Balance falls short of 20000

at OwnException.main(fileProperty.java:36)

Output:

ACC    CUST    MON
2002    Hymavathi    20000.0
2003    Janardhan    22000.0
2004    Swetha    3600.0
2005    Archana    899.0

Related Topics

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.