Home Java javaTutorial Java Basic Values: Exception Handling Keywords...

Java Basic Values: Exception Handling Keywords...

Jun 26, 2017 am 11:46 AM
java Keywords Base deal with abnormal

It is said that the Java language is very robust, such as garbage collection mechanism, memory model, exception handling, strong type conversion, cross-platform, etc., which makes the Java language popular. Today we will first talk about Java's exception handling mechanism try catch finally throw throws. Usually we seem to underestimate these five keywords. When developing application systems, good exception handling is particularly important for the later development, maintenance, upgrade, and user experience of the system.

Exceptions have a very important feature. If you never catch it from the location where the exception occurs to the main method at the top, the jvm will eventually throw the exception information for you. Oops. What's more, the thread is disconnected, and the subsequent code is no longer executed. From then on, it disappeared silently into the vast sea of ​​​​JVM. In a previous project of our company, the front-end ajax requested control to make payment. Since the control's catch threw a null pointer, the front-end page was stuck. Solution: Since the control layer is generally the top layer, it is best to catch any possible Where an exception occurs, other non-top layers can continue to throw or throw upwards. It is also best to set a timeout for each ajax.

Let’s briefly introduce throw and throws:

throw: Throw an exception in the method body. The actual exception object is usually an exception instance that you extend. , throws is placed after the method name, which means that if an exception occurs in this method, I don't want to handle it or can't handle it, and leave it to the caller to handle it. You can throw a runtime exception (unchecked) such as ClassNotFoundException, NumberFromartException, or throws or throw +try or throw+throws handles a checked exception such as: IOExcepion, SocketException, exceptions that inherit the exception class. The difference is that checked exceptions must be handled (either try or throws continue to be thrown, otherwise the compilation will not pass), while runtime exceptions do not need to be handled. The consequence of not handling them is that after an exception occurs, the jvm reports an exception message and the thread is interrupted. Lose. The throw and throws keywords are generally not recommended to be used in code, and it is recommended that all exceptions be resolved on the spot. Just know how to use it, no need to explain too much.

Try combination rules: 1, try{}catch(){} 2, try{}catch(){}finally{} 3, try{}finally{}, 1 and 2 can be used to catch There are multiple

friends, eat a few chestnuts:

1, no try combination

public class CatchExecuteJustOne {
 public void methodOne( ){
System.out.println("into methodOne method");
int one=1/0;
System.out.println("end methodOne method"); //No output. try combination, the thread has been disconnected after the error is reported
}
Public static void main(String[] args) {
CatchExecuteJustOneS cejo = new CatchExecuteJustOneS();
cejo.methodOne();

System.out.println("end main method"); //No output, no try combination, error thread has been disconnected
}
}

Output:

Into methodOne method
Exception in thread "main" java.lang.ArithmeticException: / by zero
at priv.lilei.exception.example_1.CatchExecuteJustOneS.methodOne(CatchExecuteJustOneS.java:6)
at priv. lilei.exception.example_1.CatchExecuteJustOne.main(CatchExecuteJustOne.java:19)

2.1, there is try combination case 1

public class CatchExecuteJustOne {
 public void methodOne(){
  System.out.println("into methodOne method");
 try{
  int one=1/0;
  }catch(Exception e){
  System. out.println("methodOne try to");
 }
 System.out.println("end methodOne method");
}

 public static void main(String[] args ) {
  CatchExecuteJustOne cejo = new CatchExecuteJustOne();
  cejo.methodOne();
  System.out.println("end main method");
  }
}

Output:

into methodOne method
methodOne try to
end methodOne method
end main method

2.2, there is try combination case 2

public class CatchExecuteJustOne {
public void methodOne(){
System.out.println("into methodOne method");
int one=1/0;
System.out.println("end methodOne method"); //The thread will not be executed. The error reported above is interrupted and thrown directly
}

public static void main(String[] args) {
 try{
  CatchExecuteJustOne cejo = new CatchExecuteJustOne();
  cejo.methodOne();
  }catch(Exception exception){
  System.out.println("into main method catch"); //will execute try to the above method Reported exception
 }
  System.out.println("end main method"); //Execution of try to the exception reported by the above method
 }
}

Output:

into methodOne method
into main method catch
end main method

2.3, with try case combination 3, the exception will only be caught by the most recent catch. Like switch case, the syntax is the same as if() if else(){} if()else if{}

public class CatchExecuteJustOne {
public void methodOne(){
System.out.println("into methodOne method");
try{
int one=1/0;
}catch(ArithmeticException e){
System.out.println("catch 1 ");
}catch (Exception e) {
System.out.println("catch 2");//The previous catch 1 that has been executed will not be executed
}
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();

try {
cejo.methodOne();
} catch (Exception e) {
System.out.println("man catch");//will not execute the already executed catch 1
}

System.out.println("end main method") ;
}
}

Output:

into methodOne method
catch 1
end main method

2.4 There is try combination case 4, try{}finally{} combination, the thread will be disconnected when finally does not return a value, but when there is a return value in finally, the thread will not be disconnected but the subsequent code will not be executed. This combination is recommended to be used sparingly.

//No return value

public class CatchExecuteJustOne {
 public void methodOne(){ //No return value
 System.out .println("into methodOne method");
try{
int one=1/0;
}finally{
System.out.println("into methodOne finally");
}
System.out.println("end methodOne method"); //The execution thread will not report an error and will be interrupted directly.
}

public static void main(String[] args ) {
 CatchExecuteJustOne cejo = new CatchExecuteJustOne();
 cejo.methodOne();
 System.out.println("end main method");//It will not be thrown directly if an error is reported above the execution thread and interrupted Out
}
}

Output without return value:

into methodOne method
Exception in thread "main" into methodOne finally
java.lang. ArithmeticException: / by zero
at priv.lilei.exception.example_1.CatchExecuteJustOne.methodOne(CatchExecuteJustOne.java:14)
at priv.lilei.exception.example_1.CatchExecuteJustOne.main(CatchExecuteJustOne.java:23)

There is a return value:

public class CatchExecuteJustOne {
public String methodOne(){
System.out.println("into methodOne method");
try{
System.out.println("1");
int one=1/0;
System.out.println("2");//The thread above will not be executed The error is broken and thrown directly
}finally{
System.out.println("into methodOne finally");//will output
return "1";
}
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();
cejo.methodOne();
System.out.println("end main method" );//It will be executed because there is a try above and the method has a return value
}
}

There is an output of the return value:

into methodOne method
1
into methodOne finally
end main method

2.5, the combination with finally finally will always be executed. If there is a return value, it will be executed before returning, unless there is a particularly violent behavior such as system.exit(0); or it may be disconnected, or the memory may overflow or other error.

return combination

2.5.1 In the following two cases, there are differences in assigning values ​​to variables again in catch and finally when there is no exception and when there is an exception. . If there is no exception, the assignment fails again, but if there is an exception, the assignment succeeds again.

1 No exception

public class CatchExecuteJustOne {
public String methodOne(){
String a ="";
System.out.println("into methodOne method");
try{
a="a";
return a;
}catch(ArithmeticException e){
System.out.println("catch 1");
}finally {
System.out.println(1);
a="a2"; //No error will be reported No Assign a value to a;
System.out.println(2);
}
System.out.println(3); //The above return a method will not be executed and has already returned
return a;
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();
System.out.println(cejo.methodOne());
}
}

Return output in try without exception:

into methodOne method
1
2
a

2 There is an abnormal situation

public class CatchExecuteJustOne {
public String methodOne(){
String a="";
System.out.println("into methodOne method");
try{
a ="a";
int i=1/0;
return a;
}catch(ArithmeticException e){
System.out.println("catch 1");
} finally {
System.out.println(1);
a="a2"; //If there is an exception, the value will be reassigned to variable a
System.out.println(2);
}
System.out.println(3); //The output will be that the caught exception is not returned from the first return a above but from the following return
return a;
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();
System.out.println(cejo.methodOne());
}
}

try returns an abnormal situation and outputs:

into methodOne method
catch 1
1
2
3
a2

The above is the detailed content of Java Basic Values: Exception Handling Keywords.... For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles