/*
- Exception handling 1 try-catch-finally
- 1, using the Java exception handling mechanism is exception handling program code together, separately from the normal code,
- Excessive if-else branch code of the program will lead to longer, bloated, poor readability. Thus using the exception handling mechanism. It makes the program simple, elegant, and easy to maintain.
- 2, Java provides is caught throwing exception handling model.
- Step one: throw an exception
- The program during execution exception occurs, an exception will generate class object, the object will be presented to the exception Java runtime system,
- This process is called throw (the throw) exception, once an exception is thrown object code is not executed thereafter.
- Way to create an exception object:
- 1, is automatically generated by the virtual machine: the program is running, the virtual machine detects the problem occurs program, did not find the appropriate handler if the current code,
- It will automatically create an instance of an object corresponding exception class in the background and throw - throw automatically
- 2, created manually by developers: Exception exception = new ClassCastException ();
- Creating good does not throw an exception object does not have any influence on the program, and create a common objects, like
- Step two: catch the exception
- Abnormality is an abnormality of the capture process, there are two common ways: 1, try-catch-finally 2, throws
- 3, mode 1: try-catch-finally use of
- try{
- // block of code may appear abnormal
- } Catch (Exception type variable name 1 1) {// variable name used e, can be replaced
- 1 way to handle exceptions
- } Catch (Exception Type 2 2 Variable name) {
- 2 ways to handle exceptions
- // ...} based on the actual situation, you may be provided a plurality of catch
- finally{
- // finally block will perform optional configuration, as with the default switch-case
- }
- Description:
- 1, try-catch structure can be nested.
- 2, may try to wrap exception code block, once an abnormality occurs during operation, is generated corresponding to the object class of the exception,
- Depending on the type of this object, it will match the catch statement.
- 3, once the abnormality try to match the type of abnormality of the catch, the catch will perform the processing of the statement,
- (Without finally construct) will be processed out of the current try-catch structure, the code to perform the subsequent
- 4, catch the exception type does not matter if the child's parent, any location can be, if there are child-parent relationship class, subclass write on it, otherwise it will error.
- 5, catch the two conventional methods. 1, String getMessage (), returns a string, 2printStackTrace (). The return value of type void.
- printStackTrace () will also output getMessage () information. More common
- 6, the variables are defined in the structure try local variables, a call can not be outside the braces. finally also can not be called.
- 7, to quickly generate try-catch structure, the eclipse can choose to use the right to select the code try-catch wrapped in surround with the code after the fast speed.
- 4, finally use
- 1 catch the exception of the last step is to provide a unified export exception handling by finally statement,
- Such that the control flow goes to other parts of the program before, it is possible for the unified management of the state of the program.
- 2 whether or not the abnormal event occurs in the try block, catch statement is executed,
- Catch statement whether there is an abnormality, if there is return catch statement, the finally block statement will be executed.
- 3, finally catch statement statement is optional, and
- 4, the method returns a value, if the output returns to the try-catch configuration values, and each needs to try the catch in the
- Define a return value.
- 5, where finally used, as a database connection, the input and output streams, network programming socket, can not be automatically recovered in the JVM.
- Need to manually close the code to release resources need to declare in finally, make sure that closes to prevent memory leaks.
- 5, summary
- 1:00 using the try-catch-finally compiled abnormal processing structure, so that the program is not being given at compile time, but at run time error is still possible.
- Equivalent to the use of try-catch-finally structure that may occur when compiling a delay occur until runtime.
- Abnormal more common to run 2 development, it is often abnormal Add try-catch-finally structure is not running against,
- And for compile-time anomaly, consider doing try-catch, otherwise the program can not run.
*/
package exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception_Handle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
try {
int i = 10;
num = 20;
System.out.println("请输入一个1-100范围内的整数");
int n = scan.nextInt(); //当在控制台输入小数时,报异常
if(n < 1 || n > 100) {
throw new RuntimeException("数据超出范围");//只抛出异常,没有捕获,程序不会执行后面的代码
}
System.out.println(n);
}catch(NullPointerException e) {//如果只有这个异常处理措施,则会自动抛出异常,因为异常类型不匹配
System.out.println("没有数据");
}catch(InputMismatchException a) {
a.getMessage();
System.out.println("输入数据类型错误");//异常捕获处理后,会继续执行后面的代码
}catch(Throwable e) {
System.out.println("天知道什么异常");//异常的父类写在后面,与if-else中的规则相同,包含关系中范围大的在后面
}
finally {
System.out.println("输入结束");
scan.close();
}
System.out.println(num);
// System.out.println(i);//try中的局部变量无法在外部使用
System.out.println("结束测试1");
try {
Object o = new Date();
String s = (String)o;
}catch(ClassCastException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("结束测试2");
Exception_Handle test = new Exception_Handle();
int i = test.method();
System.out.println(i);
System.out.println("结束测试3");
test.method2();
System.out.println("结束测试4");
}
public int method() {
try {
String s = null;
System.out.println(s.charAt(1));
return Integer.parseInt(s);
}catch(NullPointerException e) {
e.printStackTrace();
// int[] array = new int[] {3,2,1,0};
// System.out.println(array[4]);//catch语句中可能也有异常,不影响finally语句的输出
return 404;
}catch(Exception e) {
e.printStackTrace();
return 502;
}finally {
System.out.println("Hello");
return 12;//finally中的return值是最终输出的值
}
}
public void method2(){
FileInputStream fis = null;
try {
File file = new File("E:\\eclipse-workspace\\Contacts\\bin\\2.txt");
fis = new FileInputStream(file);
int date = fis.read();
while(date != -1) {
System.out.print((char)date);
date = fis.read();
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(fis != null) {//防止出现空指针异常,file可能无法找到,此时fis无法创建
fis.close();//当fis创建成功后,确保关闭。
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}