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!

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!