Abnormal, according to the literal meaning, means unexpected. To understand it at the code level, it prevents the current method or scope from continuing to execute. In Java, exceptions are handled as objects, and their base class is Throwable.
Several common exceptions in java:
1. Null pointer exception class: NullPointerException
An uninitialized object is called or does not exist Object. It often appears in operations such as creating images and calling arrays. For example, the image is not initialized, or the path when creating the image is wrong, etc. A null pointer appears during an array operation, which confuses the initialization of the array with the initialization of the array elements.
The initialization of the array is to allocate the required space to the array, and the elements in the initialized array have not been instantiated and are still empty, so each element needs to be initialized (if you want to call if).
2. Data type conversion exception: java.lang.ClassCastException
When trying to force downcasting on an object, but the object cannot be converted and This exception is thrown when an instance is not convertible to its subclass, as in the following code.
Object obj = new Integer(0); String str = obj;
3. No access rights: java.lang.IllegalAccessException
When the application wants to call a class, but the current method does not have access rights to the class This exception will occur. Please pay attention to this exception when using Package in the program.
4. Method parameter error: java.lang.IllegalArgumentException
For example, three of the methods g.setColor(int red, int green, int blue) If the value exceeds 255, this exception will also occur. Therefore, once we find this exception, what we have to do is to quickly check whether there is an error in the parameter passing in the method call.
5. Array subscript out-of-bounds exception: java.lang.IndexOutOfBoundsException
Check whether the subscript value of the called array or string exceeds the range of the array. Generally speaking, explicit (that is, using a constant as a subscript directly) calls are less likely to make such errors, but implicit (that is, using variables to represent subscripts) calls often cause errors.
There is another situation where the length of the array defined in the program is determined by some specific methods and is not declared in advance. At this time, check the length of the array first to avoid this exception.
6. The file has ended exception: EOFException
When the program encounters the end of the file or stream during the input process, an exception is thrown. Therefore, this exception is used to check whether the end of the file or stream has been reached
7. File not found exception: FileNotFoundException
When the program attempts to open a non-existent file for reading This exception will be thrown when writing. This exception is thrown by the constructor declaration of FileInputStream, FileOutputStream, and RandomAccessFile. Even if the file being operated exists but is inaccessible for some reason, such as opening a read-only file for writing, these construction methods will still throw an exception.
8. Exception when converting string to number: NumberFormatException
When trying to convert a String to a specified number type, and the string does not meet the number type requirements format, this exception is thrown. For example, when character data "123456" is converted into numeric data, it is allowed.
But if the character data contains non-numeric characters, such as 123#56, an exception will occur when converting to numeric type. The system will catch this exception and handle it.
9. The specified class does not exist: java.lang.ClassNotFoundException
The main consideration here is whether the name and path of the class are correct, usually the program attempts to An exception may be thrown when loading a class via a string. For example: call Class.forName; or call ClassLoad's finaSystemClass; or LoadClass;
10. Instantiation exception: java.lang.InstantiationException
When trying to pass Class The newInstance method creates an instance of a class, but the program cannot create the object through the constructor. Class object represents an abstract class, interface, array class, basic type. The class represented by this Class does not have a corresponding constructor.
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of Several common exceptions in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.
