Java program that handles exception methods
Exception is an abnormal event that disrupts the normal execution flow of the program. When an exception occurs, an object called the exception object is generated, which contains the details of the exception such as name, description, and program status. In this section we will write a java program to handle different exception methods present in java.
Exception type
There are three types of exceptions −
Checked exception − Checked exceptions are compile-time exceptions, which are checked during program compilation. These exceptions cannot be ignored and must be handled by the programmer. For example: IOException, SQLException, ClassNotFounException.
Unchecked exceptions - Unchecked exceptions are runtime exceptions, i.e. they are ignored during compilation and checked during program execution. For example: NullPointerException (null pointer exception), ArithmeticException (arithmetic exception) and ArrayIndexOutOfBoundsException (array out-of-bounds exception).
Error − Errors are unrecoverable exceptions that usually occur due to problems with the Java virtual machine or system resources. Errors, unlike exceptions, should not be caught or handled by programmers because they tell us that there is a serious problem that cannot be fixed by the program. For example: OutOfMemoryError, StackOverflowError.
Exception handling
Exception handling is the process of handling exceptions raised during program execution so that the execution flow is not interrupted. This is done using try-catch blocks in Java. The try block contains code that may throw exceptions, and the catch block contains code that handles exceptions.
We can use built-in exceptions or create custom or user-defined exceptions. Custom exceptions extend the Exception class or the RuntimeException class.
Java provides many methods to handle these exceptions. Some of these methods are -
getMessage() − This method is used to return the error message as a string. This is a method defined in the Throwable class in Java.
try { // some code that may throw an exception } catch (Exception e) { String message = e.getMessage(); System.out.println("Exception occurred: " + message);
getStackTrace() - This method returns an array of the sequence of method calls that caused the exception. This is the method defined in Throwable class in Java.
try { // some code that may throw an exception } catch (Exception e) { StackTraceElement[] st = e.getStackTrace(); for (StackTraceElement ele : st) { System.out.println(ele.toString()); } }
printStackTrace() - This method prints an array of the sequence of method calls that caused the exception. This is the method defined in Throwable class in Java.
try { // some code that may throw an exception } catch (Exception e) { e.printStackTrace(); }
Throw − 'throw' is the keyword in Java used to explicitly throw exceptions. When this keyword is executed, the normal program flow will be stopped and it will throw an exception, which will be caught by the nearest catch statement.
public void divide(int a, int b) { if (b == 0) { throw new ArithmeticException("Cannot divide by zero!"); // throws Arthemetic Exception } int result = a / b; System.out.println("Result: " + result); }
getCause() − This method returns the cause of other exceptions that raised this exception. If the cause is unknown, 'null' is returned. This is a method defined in the Throwable class in Java.
try { // some code that may throw an exception } catch (Exception e) { Throwable cause = e.getCause(); if (cause != null) { System.out.println("Cause: " + cause.toString()); } else { System.out.println("No cause found."); } }
grammar
try-catch block - try-catch block in java is used to handle exceptions. The try block contains code that may throw an exception. The catch block catches exceptions and handles them. An attempt can be followed by a set of catch blocks.
try { // Protected code } catch (ExceptionName e1) { // Catch block }
Now, we will discuss in detail the different ways of handling method exceptions in Java.
Method 1: Use a single try-catch block
In this approach, we will use a single try and a single catch block to handle the exception that occurs.
algorithm
Initialize an array with random values.
Try to access an element in the array such that the index should be greater than the length of the array. Put this code in a try block as it will throw an exception.
Once an exception occurs, use the catch() method to capture the ArrayIndexOutOfBounds exception, use the getMessage() method to print the message, and use the printStackTrace() method to print the sequence of method calls.
Example
In this example, we write the code in try and catch blocks. In the try block, we initialize an array with 5 values and access the 8th element of the array, which usually throws an exception "ArrayIndexOutOfBoundsException" . The catch block captures this exception and uses the getMessage() method to print the error message. The printStackTrace() method is used to print the method call sequence when the exception occurs.
import java.util.*; public class Main { public static void main(String[] args) { try { int[] arr = {1, 2, 3,4,5}; System.out.println(arr[8]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("An exception occurred: " + e.getMessage()); e. printStackTrace() ; } } }
Output
An exception occurred: Index 8 out of bounds for length 5 java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 5 at Main.main(Main.java:6)
Method 2: Use a single try block and multiple catch blocks
In this approach, we will use a single try and multiple catch blocks to handle the exceptions that occur.
algorithm
Declare a try block and initialize two integer variables, namely numerator and denominator. The denominator variable is initialized to 0.
Now, if the denominator value is equal to 0, an ArithmeticException is thrown.
Write multiple catch blocks to handle different exceptions.
Use different built-in methods in java and print the exception message and the exception that occurred.
示例
在此示例中,我们使用了一个 try 块,后跟多个 catch 块。如果从 try 块中抛出 ArithmeticException,则执行处理 ArithmeticException 代码的 catch 块。如果 try 块抛出 NullPointerException,则执行该特定的 catch 块。如果 catch 块不处理 try 块引发的特定异常,则执行最后一个 catch 块代码,因为它正在处理通用异常情况。从示例中,当分母值初始化为零时,我们使用“throw”关键字抛出一个 ArthemeticException,并执行处理 ArthemeticException 的 catch 块。
import java.util.*; public class Main { public static void main(String[] args) { try { int numerator = 10, denominator = 0 ; if(denominator == 0) { throw new ArithmeticException(); } } catch (ArithmeticException e) { System.out.println("ArithmeticException caught."); System.out.println("Message: " + e.getMessage()); System.out.println("Stack Trace: "); e.printStackTrace(); System.out.println("Cause: " + e.getCause()); } catch (NullPointerException e) { System.out.println("NullPointerException caught."); System.out.println("Message: " + e.getMessage()); System.out.println("Stack Trace: "); e.printStackTrace(); System.out.println("Cause: " + e.getCause()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException caught."); System.out.println("Message: " + e.getMessage()); System.out.println("Stack Trace: "); e.printStackTrace(); System.out.println("Cause: " + e.getCause()); }catch (Exception e) { System.out.println("NullPointerException caught."); System.out.println("Message: " + e.getMessage()); System.out.println("Stack Trace: "); e.printStackTrace(); System.out.println("Cause: " + e.getCause()); } } }
输出
ArithmeticException caught. Message: null Stack Trace: java.lang.ArithmeticException at Main.main(Main.java:7) Cause: null
因此,在本文中,我们讨论了处理Java编程语言中异常方法的不同方法。
The above is the detailed content of Java program that handles exception methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Common problems and solutions encountered in C# technology development Introduction: C# is an object-oriented high-level programming language that is widely used in the development of Windows applications. However, during the development process of C# technology, you may encounter some common problems. This article will introduce some common problems, provide corresponding solutions, and attach specific code examples to help readers better understand and solve these problems. 1. NullReferenceException (null reference exception) in the C# development process,

Common problems and solutions to exception handling in Python Introduction: When writing programs, it is difficult to avoid various errors and exceptions. Exception handling is a mechanism that can catch and handle these exceptions while the program is running, thereby ensuring the stability and reliability of the program. In Python, exception handling is a very important skill. This article will introduce common problems and solutions to exception handling in Python, and provide specific code examples. 1. Exception classification and common problems Grammar errors (SyntaxErr

In Java development, thread pool is a very commonly used multi-threading mechanism. It can effectively manage, control and reuse threads, improving program performance and efficiency. However, in actual development, the thread pool may be fully loaded, causing tasks to fail to execute normally. This article will discuss how to handle thread pool full exceptions to improve program stability and reliability. First, we need to understand the cause of the thread pool full exception. The main reason why the thread pool is full is that task submission exceeds the maximum number of threads set by the thread pool. When a task is submitted to a thread

How to handle exceptions and error logging in PHP development? As a very popular back-end programming language, PHP is widely used in the field of web development. During the development process, we often need to handle exceptions and record error logs in order to discover and solve problems in time. This article will introduce best practices for handling exceptions and error logging in PHP development. 1. Exception handling In PHP, an exception is a special object used to handle error situations. When the code encounters an error that it cannot handle, we can throw an exception and

Solutions to common array out-of-bounds problems in C++ require specific code examples In C++ programming, array out-of-bounds is a common error. When we access an element in an array beyond the index range of the array, it will cause undefined behavior in the program. To avoid such errors we need to adopt some solutions. Solution 1: Use array index correctly First, we need to make sure that the index of the array starts from 0. For example, an array with 5 elements has an index ranging from 0 to 4. Therefore, when accessing array elements, make sure

How to solve Java data format exception (DataFormatException) In Java programming, we often encounter various abnormal situations. Among them, data format exception (DataFormatException) is a common but also very challenging problem. This exception will be thrown when the input data cannot meet the specified format requirements. Solving this anomaly requires certain skills and experience. This article will detail how to resolve Java data format exceptions and provide some code examples

How to properly close a MySQL connection in a Java program? MySQL is a commonly used relational database management system, and Java is a widely used programming language. When developing Java programs, it is often necessary to connect to the MySQL database to perform data addition, deletion, modification and query operations. However, connecting to the database is a resource-intensive process. If the database connection is closed incorrectly, system resources will be wasted, and it may even cause performance degradation or program crash. Therefore, closing the MySQL connection correctly is a crucial

How to handle database errors in PHP? When developing PHP applications, interacting with the database is a very common and important part. However, when it comes to database operations, mistakes are inevitable. In order to deal with these errors and ensure the robustness and stability of the application, we need to handle database errors correctly. In this article, I will introduce you to some ways to handle database errors in PHP and provide specific code examples. Catching exceptions using try-catch block In PHP we can use try-ca
