Home> Java> javaTutorial> body text

Java program that handles exception methods

王林
Release: 2023-09-12 11:49:02
forward
683 people have browsed it

Java program that handles exception methods

Exceptionis 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 handlingis 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 theExceptionclass or theRuntimeExceptionclass.

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);
Copy after login

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()); } }
Copy after login

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(); }
Copy after login

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); }
Copy after login

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."); } }
Copy after login

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 }
Copy after login

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 thegetMessage()method to print the error message. TheprintStackTrace()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() ; } } }
Copy after login

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)
Copy after login

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()); } } }
Copy after login

输出

ArithmeticException caught. Message: null Stack Trace: java.lang.ArithmeticException at Main.main(Main.java:7) Cause: null
Copy after login

因此,在本文中,我们讨论了处理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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!