http://s s
`
throw:是真实抛出一个异常。【真男人】
throws:是声明可能会抛出一个异常。【瞎吆喝】
final:是修饰符,如果修饰类,此类不能被继承;如果修饰方法和变量,则表示此方法和此变量不能在被改变,只能使用。
finally:是 try{} catch{} finally{} 最后一部分,表示不论发生任何情况都会执行,finally 部分可以省略,但如果 finally 部分存在,则一定会执行 finally 里面的代码。
finalize: 是 Object 类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法。
try-catch-finally 其中 catch 和 finally 都可以被省略,但是不能同时省略,也就是说有 try 的时候,必须后面跟一个 catch 或者 finally。
finally 一定会执行,即使是 catch 中 return 了,catch 中的 return 会等 finally 中的代码执行完之后,才会执行。
1 NullPointerException 空指针异常
2 ClassNotFoundException 指定类不存在
3 NumberFormatException 字符串转换为数字异常
4 IndexOutOfBoundsException 数组下标越界异常
5 ClassCastException 数据类型转换异常
6 FileNotFoundException 文件未找到异常
7 NoSuchMethodException 方法不存在异常
8 IOException IO 异常
9 SocketException Socket 异常
----
package com.example.codet.config.exception;
/**
* 自定义年龄异常
*/
public class AgeException extends RuntimeException
{
/**
* 无参构造,有参构造
*/
public AgeException()
{
super();
}
public AgeException( String message )
{
super( message );
}
public AgeException( String message, Throwable exception )
{
super( message, exception );
}
}
package com.example.codet.random;
import com.example.codet.config.exception.AgeException;
import com.example.codet.random.effacement.entity.Student;
import java.util.Scanner;
public class ExceptionDemo
{
public static void main( String[] args )
{
Student student = new Student();
Scanner scanner = new Scanner( System.in );
System.out.println( "enter name:" );
String name = scanner.next();
while ( true )
{
try
{
System.out.println( "enter age:" );
String ageStr = scanner.next();
int age = Integer.parseInt( ageStr );
student.setName( name );
student.setAge( age );
break;
}
catch ( NumberFormatException e )
{
e.printStackTrace();
System.out.println( "enter format error" );
}
catch ( AgeException e )
{
e.printStackTrace();
System.out.println( "age range error" );
continue;
}
}
System.out.println( student );
}
}
Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Let us discuss the most important part which is the differences between Error and Exception that is as follows:
All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Java Exception Hierarchy
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
Let us discuss the above-defined listed exception that is as follows:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations.
Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
Methods to print the Exception information:
This method prints exception information in the format of the Name of the exception: description of the exception, stack trace.
Example:
|
Output
java.lang.ArithmeticException: / by zero at GFG.main(File.java:10)
The toString() method prints exception information in the format of the Name of the exception: description of the exception.
Example:
|
Output
java.lang.ArithmeticException: / by zero
The getMessage() method prints only the description of the exception.
Example:
|
Output
/ by zero
Default Exception Handling: Whenever inside a method, if an exception has occurred, the method creates an Object known as an Exception Object and hands it off to the run-time system(JVM). The exception object contains the name and description of the exception and the current state of the program where the exception has occurred. Creating the Exception Object and handling it in the run-time system is called throwing an Exception. There might be a list of the methods that had been called to get to the method where an exception occurred. This ordered list of methods is called Call Stack. Now the following procedure will happen.
Exception in thread "xxx" Name of Exception : Description ... ...... .. // Call Stack
Look at the below diagram to understand the flow of the call stack.
Illustration:
|
Output
Let us see an example that illustrates how a run-time system searches for appropriate exception handling code on the call stack.
Example:
|
Output
/ by zero
Customized Exception Handling: Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.
Tip: One must go through control flow in try catch finally block for better understanding.
Consider the below program in order to get a better understanding of the try-catch clause.
Example:
|
Output
Output explanation: In the above example, an array is defined with size i.e. you can access elements only from index 0 to 3. But you trying to access the elements at index 4(by mistake) that’s why it is throwing an exception. In this case, JVM terminates the program abnormally. The statement System.out.println(“Hi, I want to execute”); will never execute. To execute it, we must handle the exception using try-catch. Hence to continue the normal flow of the program, we need a try-catch clause.
try { // block of code to monitor for errors // the code you think can raise an exception } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // optional finally { // block of code to be executed after try block ends }
Certain key points need to be remembered that are as follows:
The summary is depicted via visual aid below as follows:
Related Articles:
Related Courses
Java Programming Foundation – Self Paced Course
Find the right course for you to start learning Java Programming Foundation from the industry experts having years of experience. This Java Programming Foundation – Self Paced Course covers the fundamentals of the Java programming language, data types, operators and flow control, loops, strings, and much more. No more waiting! Start Learning JAVA Now and Become a Complete Java Engineer!
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer: