Exceptions are some of the errors in the program, but not all errors are exceptions, and errors can sometimes be avoided.
For example, if your code lacks a semicolon, then the result is a java.lang.Error error. If you use System.out.println(11/0), then you are because you used 0 to make the divisor. , throws an exception of java.lang.ArithmeticException.
There are many reasons for exceptions, which usually include the following major categories:
- The user entered illegal data.
- The file to open does not exist.
- The connection is interrupted during network communication or the JVM memory overflows.
Some of these exceptions are due to user errors, some due to program errors, and others due to physical errors. -
To understand how Java exception handling works, you need to know the following three types of exceptions:
- Checkered anomalies: The most representative checkered anomaly is an error caused by a user error or problem, which the programmer cannot predict. For example, if you want to open a file that does not exist, an exception occurs. These exceptions cannot be simply ignored at compile time.
- Runtime exceptions: Runtime exceptions are exceptions that may be avoided by the programmer. Contrary to checkered exceptions, runtime exceptions can be ignored at compile time.
- Errors: Errors are not exceptions, but problems that are out of programmer control. Errors are usually ignored in the code. For example, when the stack overflows, an error occurs and they are undetectable during compilation.
All exception classes are subclasses inherited from the java.lang.Exception class.
The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable has a subclass Error.
Java programs usually do not catch errors. Errors typically occur when there is a serious failure, and they are outside the scope of Java program processing.
Error is used to indicate that the runtime environment has encountered an error.
For example, JVM memory overflow. In general, the program does not recover from errors.
The exception class has two main subclasses: the IOException class and the RuntimeException class.
In the Java built-in classes (described next), there are most commonly used checkered and unchecked exceptions.
Java built-in exception class
The Java language defines some exception classes in the java.lang standard package.
Subclasses of standard runtime exception classes are the most common exception classes. Because the java.lang package is loaded by default into all Java programs, most exceptions inherited from runtime exception classes can be used directly.
Java also defines some other exceptions based on each class library. The following table lists Java's non-inspection exceptions.
abnormal | description |
---|---|
ArithmeticException | This exception is thrown when an abnormal operation condition occurs. For example, an integer "divide by zero" throws an instance of this class. |
ArrayIndexOutOfBoundsException | Exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the array size, the index is an illegal index. |
ArrayStoreException | An exception thrown when trying to store an object of the wrong type into an array of objects. |
ClassCastException | This exception is thrown when trying to cast an object to a subclass that is not an instance. |
IllegalArgumentException | The exception thrown indicates that the method was passed an illegal or incorrect parameter. |
IllegalMonitorStateException | The exception thrown indicates that a thread has attempted to wait for the monitor of the object, or is trying to notify other monitors that are waiting for the object and does not specify the monitor's thread itself. |
IllegalStateException | The signal that is generated when the method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the proper state required for the requested operation. |
IllegalThreadStateException | The exception that the thread throws when it is not in the proper state required by the requested operation. |
IndexOutOfBoundsException | Indicate when an ordering index (such as sorting an array, string, or vector) is out of range. |
NegativeArraySizeException | Thrown if the application tries to create an array of negative size. |
NullPointerException | When an application attempts to use where an object is required null when Thrown |
NumberFormatException | This exception is thrown when the application tries to convert a string to a numeric type, but the string cannot be converted to an appropriate format. |
SecurityException | An exception thrown by the security manager indicates a security violation. |
StringIndexOutOfBoundsException | This exception by the String method throws, or indication index is negative, or greater than the size of the string. |
UnsupportedOperationException | Thrown when the requested operation is not supported. |
The following table lists the check exception classes that Java defines in the java.lang package.
abnormal | description |
---|---|
ClassNotFoundException | When the application tried to load the class, the corresponding class could not be found and the exception was thrown. |
CloneNotSupportedException | When you call Object class clone method clone an object, but the object's class can not be achieved Cloneable when the interface Thrown. |
IllegalAccessException | When the access to a class is denied, the exception is thrown. |
InstantiationException | When you try to use the Class class newInstance you create an instance of a class method, designated class object because it is an interface or an abstract class can not be instantiated Thrown. |
InterruptedException | A thread is interrupted by another thread and the exception is thrown. |
NoSuchFieldException | The requested variable does not exist |
NoSuchMethodException | The requested method does not exist |
Abnormal method
The following list is the main method of the Throwable class:
No. | Method and description |
---|---|
1 | Public String getMessage() Returns detailed information about the exception that occurred. This message is initialized in the constructor of the Throwable class. |
2 | Public Throwable getCause() Returns a Throwable object representing the cause of the exception. |
3 | Public String toString() Returns the cascading name of the class using the result of getMessage(). |
4 | Public void printStackTrace() Prints the toString() result and stack hierarchy to System.err, which is the error output stream. |
5 | Public StackTraceElement [] getStackTrace() Returns an array containing the stack hierarchy. The index 0 element represents the top of the stack, and the last element represents the bottom of the stack of the method call stack. |
6 | Public Throwable fillInStackTrace() Fills the Throwable object stack hierarchy with the current call stack hierarchy and adds it to any previous information in the stack hierarchy. |
Catch an exception
Use the try and catch keywords to catch exceptions. Try/catch blocks are placed where exceptions can occur.
The code in a try/catch code block is called a protection code. The syntax for using try/catch is as follows:
try { // program code }catch(ExceptionName e1) { //Catch block }
The Catch statement contains a declaration to catch the exception type. When an exception occurs in the protected code block, the catch block after the try is checked.
If an exception occurs that is contained in a catch block, the exception is passed to the catch block, which is the same as passing a parameter to the method.
Examples
The following example declares an array of two elements that throws an exception when the code tries to access the third element of the array.
ExcepTest.java file code:
// File Name: ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
The above code compile and run the output as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
Multiple capture blocks
The case where a try code block follows multiple catch code blocks is called multiple capture.
The syntax for multiple capture blocks is as follows:
try { // program code
} catch ( exception type 1 exception variable name 1 ) { // program code
} catch ( variant type 2 exception variable name 2 ) { // program code
} catch ( variant type 2 exception variable name 2 ) { // program code
}
The above snippet contains 3 catch blocks.
You can add any number of catch blocks after the try statement.
If an exception occurs in the protected code, the exception is thrown to the first catch block.
If the data type that throws an exception matches ExceptionType1, it is caught here.
If it does not match, it will be passed to the second catch block.
So, until the exception is caught or through all the catch blocks.
Examples
This example shows how to use multiple try/catch.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
Throws/throw keyword:
If a method does not catch an inspection exception, the method must be declared using the throws keyword. The throws keyword is placed at the end of the method signature.
You can also use the throw keyword to throw an exception, whether it is newly instantiated or just captured.
The following method declaration throws a RemoteException exception:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare multiple exceptions to be thrown, separated by commas.
For example, the following method declaration throws RemoteException and InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
Finally keyword
The finally keyword is used to create a block of code that executes after a try block.
Regardless of whether an exception occurs, the code in the finally code block is always executed.
In the finally code block, you can run statements such as cleanup types, etc.
Finally, the code block appears at the end of the catch code block. The syntax is as follows:
try { // program code
} catch ( exception type 1 exception variable name 1 ) { // program code
} catch ( variant type 2 exception variable name 2 ) { // program code
} finally { // program code
}
Examples
ExcepTest.java file code:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
The above example compiled and run results are as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
Note the following:
- Catch cannot exist independently of try.
- Adding a finally block after try/catch is not mandatory.
- The try code cannot have neither a catch block nor a finally block.
- No code can be added between try, catch, finally blocks.
Declaring custom exceptions
In Java you can customize exceptions. The following points need to be kept in mind when writing your own exception class.
- All exceptions must be subclasses of Throwable.
- If you want to write an inspection exception class, you need to extend the Exception class.
- If you want to write a runtime exception class, you need to extend the RuntimeException class.
You can define your own exception class like this:
Class MyException extends Exception { }
The only exception class created by inheriting an Exception class is an inspection exception class.
The following InsufficientFundsException class is a user-defined exception class that inherits from Exception.
An exception class, like any other class, contains variables and methods.
Examples
The following example is a simulation of a bank account. Through the identification of the bank card number, it is possible to save and withdraw money.
InsufficientFundsException.java file code:
// Filename InsufficientFundsException.java
import java . io .*;
// Custom exception classes, inheriting Exception classes
public class InsufficientFundsException extends Exception {
// here amount is used to store the money that is lacking when an exception
//occurs (extracting money more than the balance) private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
// here amount is used to store the money that is lacking when an exception
//occurs (extracting money more than the balance) private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
To show how to use our custom exception class,
Including an withdraw() method in the following CheckingAccount class throws an InsufficientFundsException.
CheckingAccount.java file code:
// File Name CheckingAccount.java
import java . io .*;
// This type of analog bank account
public class CheckingAccount {
// balance is balance, number is card number private double balance ; private int number ; public CheckingAccount ( int number ) {
this . number = number ; }
// method : save money public void deposit(double amount) { balance += amount; }
// method: take money public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } // method: return balance public double getBalance ( ) {
return balance ; }
// method: return card number public int getNumber ( ) {
return number ; }
}
// balance is balance, number is card number private double balance ; private int number ; public CheckingAccount ( int number ) {
this . number = number ; }
// method : save money public void deposit(double amount) { balance += amount; }
// method: take money public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } // method: return balance public double getBalance ( ) {
return balance ; }
// method: return card number public int getNumber ( ) {
return number ; }
}
The following BankDemo program demonstrates how to call the deposit() and withdraw() methods of the CheckingAccount class.
BankDemo.java file code:
// File name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Compile the above three files and run the program BankDemo. The results are as follows:
Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)
General exception
Two types of exceptions and errors are defined in Java.
- JVM (Java Virtual Machine ) exceptions: Exceptions or errors thrown by the JVM. For example: NullPointerException class, ArrayIndexOutOfBoundsException class, ClassCastException class.
- Program-level exceptions: Exceptions thrown by programs or API programs. For example, the IllegalArgumentException class, IllegalStateException class.
Comments
Post a Comment