search
HomeJavajavaTutorialJava program that handles exception methods
Java program that handles exception methodsSep 12, 2023 am 11:49 AM
exception handlingjava programexception method

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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C#技术开发中遇到的常见问题及解决方法C#技术开发中遇到的常见问题及解决方法Oct 08, 2023 pm 01:06 PM

C#技术开发中遇到的常见问题及解决方法导语:C#是一种面向对象的高级编程语言,被广泛应用于Windows应用程序的开发。然而,在C#技术开发过程中,可能会遇到一些常见的问题。本文将介绍一些常见问题,并提供相应的解决方法,并且附上具体的代码示例,以帮助读者更好地理解和解决这些问题。一、NullReferenceException(空引用异常)在C#开发过程中,

Python中异常处理的常见问题及解决方法Python中异常处理的常见问题及解决方法Oct 09, 2023 am 08:56 AM

Python中异常处理的常见问题及解决方法引言:在编写程序时,很难避免出现各种各样的错误和异常。异常处理是一种机制,可以在程序运行时捕获和处理这些异常,从而保证程序的稳定性和可靠性。在Python中,异常处理是一项非常重要的技能,本文将介绍Python中异常处理的常见问题和解决方法,并提供具体的代码示例。一、异常的分类及常见问题语法错误(SyntaxErr

如何在PHP开发中处理异常和错误日志记录?如何在PHP开发中处理异常和错误日志记录?Nov 02, 2023 am 09:27 AM

如何在PHP开发中处理异常和错误日志记录?PHP作为一种非常流行的后端编程语言,广泛应用于Web开发领域。在开发过程中,我们经常需要处理异常和记录错误日志,以便及时发现和解决问题。本文将介绍如何在PHP开发中处理异常和错误日志记录的最佳实践。一、异常处理在PHP中,异常是一种用于处理错误情况的特殊对象。当代码遇到无法处理的错误时,我们可以抛出一个异常,并在合

如何处理Java线程池满载异常如何处理Java线程池满载异常Jun 30, 2023 am 10:09 AM

在Java开发中,线程池是一种非常常用的多线程处理机制。它能够有效地管理、控制和复用线程,提高程序的性能和效率。然而,在实际开发中,线程池可能会遇到满载的情况,导致任务无法正常执行。本文将讨论如何处理线程池满载异常,以提高程序的稳定性和可靠性。首先,我们需要了解线程池满载异常的原因。线程池满载的主要原因是任务提交超过了线程池设置的最大线程数。当任务提交到线程

C++中常见的数组越界问题解决方案C++中常见的数组越界问题解决方案Oct 08, 2023 pm 12:33 PM

C++中常见的数组越界问题解决方案,需要具体代码示例在C++编程中,数组越界是一个常见的错误。当我们在访问数组中的元素时超出了数组的索引范围,就会导致程序出现未定义的行为。为了避免这类错误,我们需要采取一些解决方案。解决方案一:正确使用数组索引首先,我们需要明确数组的索引是从0开始的。例如,一个有5个元素的数组,索引范围是0到4。因此,在访问数组元素时,确保

Java程序中关闭MySQL连接的正确方法是什么?Java程序中关闭MySQL连接的正确方法是什么?Jun 30, 2023 pm 09:17 PM

如何在Java程序中正确关闭MySQL连接?MySQL是一个常用的关系型数据库管理系统,而Java是一种广泛使用的编程语言。在开发Java程序时,经常需要连接到MySQL数据库来进行数据的增删改查操作。然而,连接数据库是一个资源消耗较大的过程,如果不正确地关闭数据库连接,会浪费系统资源,甚至可能导致性能下降或程序崩溃。因此,正确关闭MySQL连接是一个至关重

如何解决Java数据格式异常(DataFormatException)如何解决Java数据格式异常(DataFormatException)Aug 27, 2023 am 10:14 AM

如何解决Java数据格式异常(DataFormatException)在Java编程中,我们经常会遇到各种异常情况。其中,数据格式异常(DataFormatException)是一个常见但也很具挑战性的问题。当输入的数据无法满足指定的格式要求时,就会抛出这个异常。解决这个异常需要一定的技巧和经验。本文将详细介绍如何解决Java数据格式异常,并提供一些代码示例

刨析Vue的服务器端通信策略:如何处理错误和异常刨析Vue的服务器端通信策略:如何处理错误和异常Aug 11, 2023 am 09:12 AM

刨析Vue的服务器端通信策略:如何处理错误和异常在开发Web应用程序时,与服务器进行通信是必不可少的一项任务。Vue.js作为一种流行的前端框架,提供了一套强大的工具和方法来处理与服务器端的通信。在这篇文章中,我们将重点探讨Vue的服务器端通信策略,并着重讨论如何在处理错误和异常时有效地利用这些策略。在Vue中,我们通常使用axios来处理服务器端通信。Ax

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.