search
HomeJavajavaTutorialThe use of try and catch code blocks for exception handling in Java

Usage of Java try and catch
Although the default exception handlers provided by the Java runtime system are useful for debugging, usually you want to handle exceptions yourself. This has two benefits. First, it allows you to correct errors. Second, it prevents the program from terminating automatically. Most users are annoyed (to say the least) by having a stack trace printed when the program terminates and whenever an error occurs. Fortunately, this is easily avoidable.

To prevent and handle a runtime error, just put the code you want to monitor into a try block. Immediately following the try block, include a catch clause that specifies the type of error you wish to catch. Accomplishing this task is simple. The following program contains a try block and a catch clause that handles ArithmeticException exceptions caused by division by zero.

class Exc2 {
  public static void main(String args[]) {
    int d, a;
    try { // monitor a block of code.
      d = 0;
      a = 42 / d;
      System.out.println("This will not be printed.");
    } catch (ArithmeticException e) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}

The program output is as follows:

Division by zero.
After catch statement.

Note that the call to println() in the try block is never executed. Once an exception is raised, program control is transferred from the try block to the catch block. Execution never "returns" from the catch block to the try block. Therefore, "This will not be printed."

will not be displayed. Once the catch statement is executed, program control continues from the line below the entire try/catch mechanism.

A try and its catch statement form a unit. The scope of the catch clause is limited to the statements defined before the try statement. A catch statement cannot catch an exception raised by another try statement (except in the case of nested try statements).

Statement declarations protected by try must be within a curly brace (that is, they must be in a block). You cannot use try alone.

The purpose of constructing the catch clause is to resolve the exception and continue running as if the error did not occur. For example, in the following program, each iteration of the for loop yields two random integers. These two integers are divided by each other, and the result is used to divide 12345. The final result is stored in a. If a division operation results in a divide-by-zero error, it is caught, the value of a is set to zero, and the program continues.

// Handle an exception and move on.
import java.util.Random;
 
class HandleError {
  public static void main(String args[]) {
    int a=0, b=0, c=0;
    Random r = new Random();
 
    for(int i=0; i<32000; i++) {
      try {
        b = r.nextInt();
        c = r.nextInt();
        a = 12345 / (b/c);
      } catch (ArithmeticException e) {
        System.out.println("Division by zero.");
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

Display an exception description

Throwable overloads the toString() method (defined by Object), so it returns a string containing the exception description. You can display a description of an exception by passing it a parameter in println(). For example, the catch block of the previous program could be rewritten as

catch (ArithmeticException e) {
  System.out.println("Exception: " + e);
  a = 0; // set a to zero and continue
}

When this version replaces the version in the original program and the program is run under the standard javaJDK interpreter, each divide-by-zero error displays the following message:

Exception: java.lang.ArithmeticException: / by zero

Although it has no special value in context, the ability to display an exception description can be valuable in other situations - especially when you are experimenting and debugging exceptions.

Use of Java multiple catch statements
In some cases, multiple exceptions may be caused by a single code segment. To handle this situation, you can define two or more catch clauses, each catching a type of exception. When an exception is raised, each catch clause is checked in turn, and the first one matching the exception type is executed. When a catch statement is executed, other clauses are bypassed and execution continues from the code after the try/catch block. The following example designs two different exception types:

// Demonstrate multiple catch statements.
class MultiCatch {
  public static void main(String args[]) {
    try {
      int a = args.length;
      System.out.println("a = " + a);
      int b = 42 / a;
      int c[] = { 1 };
      c[42] = 99;
    } catch(ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    } catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index oob: " + e);
    }
    System.out.println("After try/catch blocks.");
  }
}

The program is run under the starting condition without command line parameters, resulting in a divide-by-zero exception because a is 0. If you provide a command line argument, it will survive and set a to a value greater than zero. But it will cause an ArrayIndexOutOf BoundsException exception because the length of the integer array c is 1 and the program tries to assign a value to c[42].

The following is the output of the program running in two different situations:

C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

When you use multiple catch statements, it is important to remember that exception subclasses must be used before any of their parent classes. of. This is because using the catch statement of the parent class will catch exceptions of this type and all its subclasses. This way, if the child class is behind the parent class, the child class will never arrive. Moreover, unreachable code in Java is a bug. For example, consider the following program:

/* This program contains an error.
A subclass must come before its superclass in a series of catch statements. If not,unreachable code will be created and acompile-time error will result.
*/
class SuperSubCatch {
  public static void main(String args[]) {
    try {
      int a = 0;
      int b = 42 / a;
    } catch(Exception e) {
      System.out.println("Generic Exception catch.");
    }
    /* This catch is never reached because
    ArithmeticException is a subclass of Exception. */
    catch(ArithmeticException e) { // ERROR - unreachable
      System.out.println("This is never reached.");
    }
  }
}

If you try to compile this program, you will receive an error message stating that the second catch statement will not arrive because the exception has already been caught. Because ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-oriented errors, including ArithmeticException. This means the second catch statement will never execute. To modify the program, reverse the order of the two catch statements.

For more articles related to the use of try and catch code blocks for exception handling in Java, please pay attention to the PHP Chinese website!


Statement
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
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor