First of all, there are two main ways to handle exceptions: one is try catch
, and the other is throws
.
1. Put code that may cause exceptions in try catch
try{}. Put in catch{} the processing after catching the exception. Among them, the function of e.printStackTrace()
in catch is to print the location and reason of the program error on the console. Only when an exception occurs in the code in the try block will it go to the catch block.
Some exception captures will add finally
. Regardless of whether the exception in the try block is caught or not, the finally block will be executed at the end, unless there is system.exit(( 0)
(system.exit(0) is used to exit the virtual machine).
Online learning video sharing: java online tutorial
2. Throw and throws
throw
It is a statement that throws an exception. It appears inside the function and is used to throw a specific exception instance. The statement after throw is executed has no effect and is transferred directly to the exception handling stage.
Examples are as follows:
throws
is a function method that throws exceptions. It is usually written in the head of the method to throw Some exceptions are not resolved by themselves, but are thrown to the caller of the method for resolution (try catch
).
Examples are as follows:
If you want to know more related articles, you can visit: Getting Started with Java
The above is the detailed content of Examples of how to handle exceptions in java. 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

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

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

Dreamweaver Mac version
Visual web development tools
