chap05-java exception
- 格式:pdf
- 大小:242.45 KB
- 文档页数:40
Java异常——异常分类、声明检查型异常⼀、异常的分类1、在Java程序设计语⾔中,异常对象都是派⽣于Throwable类的⼀个类的实例。
如果Java的内置类不能满⾜需求,⽤户还可以创建⾃⼰的异常类。
2、异常分为两⽀,Error和Exception。
Error类层次描述了Java运⾏时系统的内部错误和资源耗尽错误。
这种情况很少出现,如果出现了这种情况,就只能通知⽤户并妥善地终⽌程序。
Exception类是应该重点关注的层次结构。
3、Exception类分解成两个分⽀:⼀⽀派⽣于RuntimeException,另⼀⽀派⽣于其他异常。
派⽣于RuntimeException的异常包括以下问题:“如果出现RuntimeException异常,那么⼀定是你的问题”☛错误的强制类型转换☛数组访问越界☛访问null指针不是派⽣于RuntimeException的异常包括以下问题:⼀般是I/O错误这类问题导致的☛试图超越⽂件末尾继续读取⽂件☛试图打开不存在的⽂件☛试图根据给定的字符串查找Class对象,⽽这个字符串表⽰的类不存在。
4、检查型异常和⾮检查型异常。
Java语⾔规范将派⽣于Error或RuntimeException类的所有异常称为⾮检查型异常(unchecked),所有其他类型的异常称为检查型异常(chcked)。
编译器会检查你是否为所有的检查型提供了异常处理器。
⼆、声明检查型异常public FileInputStream(String name)throws FileNotFoundException这个声明是标准类库中FileInputStream类的⼀个构造器的声明。
这个声明表⽰构造器根据给定的String参数产⽣⼀个FileInputStream对象,但也有可能抛出FileNotFoundException异常。
如果发⽣了糟糕的情况,构造器不会初始化⼀个新的FileInputStream对象,⽽是抛出⼀个FileNotFoundException类对象,如果抛出了这样⼀个异常对象,系统会开始搜索知道如何处理FileNotFoundException对象的异常处理器。
一、介绍随着人工智能技术的不断发展,自然语言处理领域也迎来了许多创新。
GPT-3.5是由Open本人开发的最新一代自然语言处理模型,具有极强的语言理解和生成能力。
而Java作为一种广受欢迎的编程语言,在业界被广泛应用于各种软件开发和系统集成。
本文将介绍如何使用Java编程语言调用GPT-3.5模型,并结合实际案例进行详细说明。
二、GPT-3.5模型简介GPT-3.5是Open本人研发的一款自然语言处理模型,它具有1750亿个参数,比前一代模型GPT-3的1000亿个参数更加强大。
GPT-3.5能够对输入的文本进行语义理解,并生成具有逻辑、连贯和合乎语境的文本输出。
这一模型在文本生成、语言理解和对话系统等领域具有广泛的应用前景。
三、Java调用GPT-3.5的基本原理1. GPT-3.5的API接口Open本人提供了GPT-3.5的API接口,开发者可以通过向该接口发送HTTP请求来调用模型的功能。
API接口支持多种编程语言,包括Java,使得开发者能够方便地集成GPT-3.5模型到其应用程序中。
2. Java中的HTTP请求Java语言本身提供了丰富的网络编程功能,可以通过Java的网络编程库来发送HTTP请求,并获取API接口返回的结果。
这使得在Java中调用GPT-3.5模型变得简单和高效。
四、Java调用GPT-3.5的实现步骤1. 获取Open本人的API密钥开发者需要在Open本人全球信息湾注册账号,并获取API密钥。
API 密钥是调用GPT-3.5模型的凭证,具有很高的安全性和保密性。
在获取API密钥后,开发者可以在Java程序中使用该密钥来进行HTTP请求。
2. 编写Java代码在Java程序中,开发者可以使用Java的网络编程库或第三方的HTTP 客户端库来发送HTTP请求。
还需要在代码中设置请求头、请求体等参数,以及处理返回的结果。
通过这些步骤,开发者就能够实现在Java中调用GPT-3.5模型的功能。
ng.NullPointerException原因是:有空指针,有地址没赋值2.Exception in thread "main" ng.ArithmeticException: / by zero原因是除数是03.ArrayIndexOutOfBoundsException原因是:数组越界原因是:数字格式化有问题5.Unhandled exception type Exception原因是:没有进行异常处理6.进行国际化操作的时候遇到这样的错误:Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name Message, locale zh_CN答:因为在命令提示符中,是没有错误的解决方法是:在myeclipse中,会出现这个错误1.初步学习最近在学习ResourseBundle时遇到了“Can't find bundle for base name ”这个错误搞了很久才解决了。
原因就是类路径问题要将属性文件放在类路径中!百度里很多都是教程但没有涉及到解决方法! 2.中文显示:测试文件java 代码package com.lht.ResourseBundleStudy;import java.util.ResourceBundle;public class ResourseBundleDemo {public static void main(String[] args) {ResourceBundle resource =ResourceBundle.getBundle("test");System.out.print(resource.getString("msg0") + "!");System.out.println(resource.getString("msg1") + "!"); }}test.propertiesmsg0="Hello World"msg1="da jia hao"开始自己测试的时候:将属性文件放在bin/下也试过也不行无赖中就在google中搜索了一下终于在sun的java论坛()中找到了线索下面是帖子的内容:I've solved the problem the best way possible. Basically what i've done is added a new class folder named config to the project home dir. Then i added this classfolder to the classpath in project properties. After doing all of this you only need to reference the properties file by "Email".Hope this helps anyone else who is having similiar problems.基本意思就是在src下建立classes(名字无所谓)文件夹将属性文件存放在下面,然后将这个文件夹加入类路径中!运行就可以了:加入类路径的方法:你的工程文件夹->properties->选择Libraries选项卡->Add Class Folder将刚才建立的文件夹加入就可以了!结果如下:"Hello World"!"da jia hao";!2.中文显示在classes目录下建立message_CH.properties内容如下:ms0="大家好"同样用上面的测试文件!结果如下:"?ó????"!乱码怎么回事啊!在百度里搜索后找到了答案有以为网友写的很清楚:下面引用如下:原理Property文件中,使用的编码方式根据机器本身的设置可能是GBK或者UTF-8。
∙101 Internal JVM error.∙102 Invalid code in file system. The .cod files in the handheld have been checked for modification and it has been determined that there is a problem with one or more .cod files.∙103 The starting address for the boot .cod file cannot be found.This might mean that a boot .cod file has not been installed on the handheld, or that its format is invalid or corrupt.∙104 An uncaught Java exception was thrown in the Java code and diagnosed by the JVM. Execution can be continued or the handheld can be attached to a debugger on a desktop through a serial or USB cable. The event log should contain the traceback of the thrown exception.∙105 An OS file system API returned an error status for a certain operation. This can indicate a corrupt file system or an error in the JVM.∙106 An error has been detected in the graphics system of the handheld.∙107 Internal JVM error.∙108 Internal JVM error.∙109 Internal OS error.∙110 Non-idle event downtime error. A problem has been detected in the accumulation of JVM down time that represents how long the JVM has been idle. This indicates an error in either the OS code or the JVM code.∙200 Application manager threw an uncaught exception. The application manager event thread threw an uncaught exception and so cannot continue running.∙201 Initialization of the cryptographic system failed and the handheld cannot continue to operate.∙202 An attack on the key store has been detected, and the handheld cannot continue to operate.∙203 The application manager console process, usually the Home screen ribbon, has failed, like due to an uncaught exception. ∙501 Internal error.∙502 All processes exited. The last Java process has terminated, and there is nothing left to execute.∙503 Internal error.∙504 Internal error.∙505 Internal error.∙506 An uncaught Java exception was thrown in the initial VM Java thread thus killing the only live thread in the system. The event log contains the traceback for the exception.∙507 A dependency on a .cod file could not be satisfied due to a missing .cod file. Load the missing .cod file onto the handheld.∙508 Invalid object. A problem has been detected with a debugger command to the VM.∙516 Error occurred during garbage collection, which might indicatea corrupted file system.∙510 All threads are waiting on objects, which results in a deadlock.The system cannot recover from this state since no thread can release a lock.∙511 A problem has occurred during debugging.∙515 The reachable objects form a group that cannot be represented properly by the VM because there are too many objects or the total size of the objects is too large.∙516 When committing a persistent object, the VM found that the persistent store id counter has reached its limit. The object was not committed.∙517 An inconsistency has been detected in the VM persistent object store.∙518 Internal error.∙519 Internal error.∙520 Internal error.∙521 Indicates that Object.wait() has been executed by a thread that holds a lock on another object; occurs only in simulator if the JvmDebugWaits application switch.∙522 A thread has acquired two locks on objects in an order that doesn’t match the order that previous locks for the two types were acquired, which indicates a future potential deadlock situation;reported only in the simulator when the JvmDebugLocks application switch is set.∙523 A critical Java process has died and the device cannot continue to operate normally.∙524 An object has been marked as recovered by the Low Memory Manager but it was not freed during a garbage collection. This is only checked in the simulator under the control of the JvmDebugLMM application switch.∙525 Bad persistent object. An auto-commit operation during a garbage collection has detected a non-persistent object reachable from the persistent store root. The type of the object has been output into the event log.∙526 The class definition for ng.Object cannot be found. ∙527 The class definition for ng.String cannot be found. ∙528 The file system is corrupted. Data on the handheld is unrecoverable.∙529 The file system is corrupted. An attempt is going to be made to recover data, but some data might be lost.∙530 Internal JVM error.∙531 Flash memory has been exhausted.∙532 A JVM assertion has been violated. This error can occur only in the simulator, not on an actual handheld.∙■101内部JVM错误。
ioexception类型-回复什么是IOException?IOException是Java编程语言中的一个异常类,它是由Java的java.io 包定义的。
它是ng.Exception类的子类。
IOException表示输入或输出操作失败的异常情况。
当Java程序无法正常读取或写入数据流时,就会抛出IOException。
IOException是一个广泛的异常类型,它涵盖了各种文件和网络操作中可能出现的错误情况。
例如,当试图打开不存在的文件或目录,或者无法访问文件或目录时,会发生IOException。
它还可以用于表示网络连接中的各种异常,例如当尝试连接到无效的主机或端口时。
IOException类提供了一些方法来获取有关错误的详细信息。
这些方法包括getMessage(),可以返回错误消息的详细描述;getCause(),可以返回导致IOException的根本原因。
下面我们将逐步探讨IOException类型及其相关操作。
1. 异常处理在处理IOException时,应使用try-catch块来捕获并处理异常。
这可以防止程序崩溃,并允许我们在出错时采取适当的措施。
例如,当尝试打开一个不存在的文件时,会抛出FileNotFoundException,它是IOException的子类之一。
我们可以使用try-catch块来捕获这个异常,然后在catch块中执行适当的处理逻辑,例如输出错误消息或采取其他操作以修复问题。
下面是一个简单的示例代码:javatry {尝试打开文件File file = new File("test.txt");FileReader reader = new FileReader(file);} catch (FileNotFoundException e) {文件不存在的异常处理逻辑System.out.println("文件不存在!");}在这个例子中,我们尝试打开一个名为"test.txt"的文件。
Java——异常(Exception)A.1. 异常分类所有异常都是由Throwable继承⽽来,但在下⼀层⽴即分解为两个分⽀:Error和Exception Error异常:该层次异常描述了系统运⾏时内部错误和资源耗尽错误。
应⽤程序不该抛出这种类型的对象,如果出现这种错误,除了通告给⽤户,并尽⼒使程序安全推出,再也⽆能为了。
这种情况很少出现。
Exception异常:该层次异常⼜分解为两个分⽀,⼀个派⽣于RuntimeException;另⼀个分⽀包含其他异常。
划分为两个分⽀的规则是:由程序错误导致的异常属于RuntimeException;⽽程序本⾝没问题,但是由于像I/O错误这类问题导致的异常属于其他异常。
Java语⾔规范将派⽣于Error类或RuntimeException类的所有异常称为⾮受(unchecked)查异常,所有其他的异常称为受查(checked)异常。
2. 声明受查异常下⾯四种情况应该抛出异常:1. 调⽤⼀个抛出受查异常的⽅法,例如,FileInputStream构造器。
2. 程序运⾏过程中发现错误,并且利⽤throw语句抛出⼀个受查异常。
3. 程序出现错误。
4. java虚拟机的运⾏时库出现的内部错误。
如果出现前两种情况之⼀,则必须告诉调⽤这个⽅法的程序员有可能抛出异常。
ss对于那些可能被别⼈使⽤的java⽅法,应该根域异常规范,在⽅法的⾸部声明这个⽅法可能抛出的异常。
如果有可能抛出多个异常,应该逗号分开例如:throws FileNotFoundException,EOFException但是不需要声明Error错误,任何程序都有抛出那些异常的潜能,⽽我们对其没有任何控制能⼒。
同样也不该声明从RuntimeException继承的那些⾮受查异常。
警告:如果在⼦类中覆盖了超类的⼀个⽅法,⼦类⽅法中声明的受查异常不能⽐超类⽅法中声明的异常更通⽤(也就是说,⼦类⽅法中可以抛出更特定的异常,或者根本不抛出任何异常)。
JAVA聊天程序设计代码及报告import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Scanner;public class ChatClientpublic static void main(String[] args)final String HOST_NAME = "localhost";final int PORT_NUMBER = 1234;trySocket socket = new Socket(HOST_NAME, PORT_NUMBER);System.out.println("Connected to chat server!");BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream());PrintWriter writer = new PrintWriter(socket.getOutputStream(, true);// read user input in a separate threadThread inputThread = new Thread(( ->Scanner scanner = new Scanner(System.in);while (true)String userInput = scanner.nextLine(;writer.println(userInput);}});inputThread.start(;// continuously read server responsesString serverResponse;while ((serverResponse = reader.readLine() != null)System.out.println("Server: " + serverResponse);}} catch (Exception e)System.out.println("Error: " + e.getMessage();}}该聊天程序是一个基于TCP协议的客户端程序,使用了Java Socket 进行通信。
Java---异常ng.Throwable|----Exception:程序可以处理的异常|----Error:与虚拟机相关问题,系统崩溃,虚拟机问题,内存不足,内存堆栈溢出……建议程序停止。
异常:程序在运行时出现不正常情况,java对不正常情况进行描述后的对象体现。
-------------------------------------------------常见的处理方法:|---String getMessage();|---String toString()|---void printStackTrace();(jvm默认的异常处理机制其实就是调用printStackTrace());-------------------------------------------------异常的处理:try { …}catch(异常类变量) {//处理几个异常就声明几个catch…(多个catch块中的异常出现继承关系时,父类catch块要放在子类catch下面)}finally{ …}//非必须,但声明后一定会执行,一般用于释放资源Eg:数据库异常时无法关闭数据库,可使用finally,对资源的关闭例外:System.exit(0)系统退出,jvm结束,finally不执行。
------------------------------------------------异常的声明(throws)编写Demo时,代码可能发生异常通过throws声明功能可能会出现的异常:Eg: intdiv(int a ,int b)throws Exception{Return a/b;//我们知道b=0时会抛出ArithmeticException;}public static void main(String [] args){try{ …} catch(Exception e){ …}}(catch处理时,最好要有具体的处理形式,例如异常日志文件等)-------------------------------------自定义异常:项目中会出现持有的问题,而这些问题并未被java所描述并封装对象时,可将这些问题进行自定义的异常封装(自定义类继承异常类)继承异常的原因:因为异常类和异常对象都被抛出,他们都具备可抛性,这个可抛性是Throwable体系特点,只有这个体系中的类和对象才可以被throws 和throw操作------------------------------假设:a/b中,除数如果是负数和0都认为是错的异常描述。
ioexception类型【实用版】目录1.IOException 类型的概念2.IOException 类型的分类3.IOException 类型的使用示例4.IOException 类型的优缺点正文1.IOException 类型的概念IOException 类型是 Java 中处理的输入输出异常的基础类型,它表示在程序执行过程中,由于输入输出操作失败而引发的异常。
IOException 类型可以处理文件读写操作、网络编程等多种场景下的异常。
2.IOException 类型的分类IOException 类型可以分为以下几类:(1) FileNotFoundException:文件未找到异常。
当程序试图访问一个不存在的文件时,抛出该异常。
(2) IOException:输入输出异常。
当程序在执行输入输出操作时发生错误,如读写文件失败、网络连接中断等,抛出该异常。
(3) EOFException:文件已结束异常。
当程序试图从已结束的输入流中读取数据时,抛出该异常。
(4) MalformedURLException:URL 格式错误异常。
当程序试图访问一个格式错误的 URL 时,抛出该异常。
(5) UnknownHostException:未知主机异常。
当程序试图访问一个未知的主机时,抛出该异常。
(6) ConnectException:连接异常。
当程序在建立网络连接时发生错误,如无法连接到服务器等,抛出该异常。
(7) SocketException:套接字异常。
当程序在操作套接字时发生错误,如套接字关闭异常等,抛出该异常。
3.IOException 类型的使用示例下面是一个使用 IOException 的示例:```javaimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class IOExceptionDemo {public static void main(String[] args) {try {BufferedReader reader = new BufferedReader(new FileReader("nonexistentfile.txt"));String line = reader.readLine();reader.close();} catch (FileNotFoundException e) {System.out.println("文件未找到:" +e.getMessage());} catch (IOException e) {System.out.println("输入输出异常:" +e.getMessage());}}}```4.IOException 类型的优缺点优点:IOException 类型可以帮助程序员处理各种输入输出异常,提高了程序的健壮性。
Java 异常outlinez程序错误概念z程序错误原因分析z Java异常类介绍z Java异常处理机制: try, catch, finally, throw, throwsz RuntimeExceptionz Checked & unchecked Exceptionz常见的异常处理方法:getMessage,printStackTrace z Java exception class hierarchyz Method of finding errors程序错误概念z程序中的错误分类:编译错误:又称为”语法错误”,java编译器发现的错误运行错误:程序运行时出现的严重错误,导致程序停止运行逻辑错误:计算机无法识别,语法正确,程序逻辑错误。
z异常的概念:指程序在执行过程中出现程序本身没有预料的情况,从而导致程序错误结束。
比如说:用户输入出错所需文件找不到运行时磁盘空间不够内存不够算术运算错(数的溢出,被零除…)数组下标越界z使用异常机制的目的:用来在发生运行异常时告诉程序如何控制自身的运行,以防止错误的进一步恶化异常类的层次结构异常处理z打开一个不存在的文件、网络连接中断、数组下标越界、正在加载的类文件丢失等都会引发异常。
z Java中的异常类定义了程序中遇到的轻微的错误条件。
z Java中的错误类定义了程序中不能恢复的严重错误条件。
如内存溢出、类文件格式错误等。
这一类错误由Java运行系统处理,不需要我们去处理。
异常处理z Java程序在执行过程中如出现异常,会自动生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。
z当Java运行时系统接收到异常对象时,会寻找能处理这一异常的代码并把当前异常对象交给其处理,这一过程称为捕获(catch)异常。
z如果Java运行时系统找不到可以捕获异常的方法,则运行时系统将终止,相应的Java程序也将退出。
z try/catch/finally语句。
异常处理z对于RuntimeException,通常不需要我们去捕获,这类异常由Java运行系统自动抛出并自动处理。
z如果父类中的方法抛出多个异常,则子类中的覆盖方法要么抛出相同的异常,要么抛出异常的子类,但不能抛出新的异常(注:构造方法除外)。
z我们可以在方法声明时,声明一个不会抛出的异常,Java编译器就会强迫方法的使用者对异常进行处理。
这种方式通常应用于abstract base class和interface中。
异常的优势z与传统的错误处理方法相比异常的优点:1.把错误代码从常规代码中分离出来2. 把错误传播给调用堆栈3. 按错误类型分组4. 系统提供了对于一些无法预测的错误的捕获和处理5. 克服了传统方法的错误信息有限的问题method1method2method3method4产生异常传递处理异常Java异常处理机制z Every method is allowed to have two exit pathsNo errors occur–Method exits in the normal way–Returns a value–Control passed to the calling code.If errors occur–Method exits via an alternative exit path(exceptionhandling path)–Throws an object that encapsulates the error information–Control passed to exception mechanism that searches foran appropriate exception handler to deal with the errorcondition异常(Exception)z运行系统从错误发生处开始寻找处理错误的程序段The exception handler chosen is said to catch the exception(捕获异常)捕获异常的过程可以沿方法调用的逆向顺序寻找z 为什么采用异常(Exception) 隔绝正常代码和错误处理代码 对错误进行分类,针对不同错误作不同处理异常(Exception)readFile {try {open the file;determine its size;allocate that much memory;read the file into memory;close the file;} catch (fileOpenFailed) {doSomething;} catch (sizeDeterminationFailed) {doSomething;} catch (memoryAllocationFailed) {doSomething;} catch (readFailed) {doSomething;} catch (fileCloseFailed) {doSomething;}}z沿方法调用堆栈逆向(回溯)传播错误z 异常冒泡异常(Exception)method1 {try {call method2;} catch (exception) {doErrorProcessing;}}method2 throws exception {call method3;}method3 throws exception {call readFile;}异常(Exception)异常处理器(exception handler)–try–catch–finally异常的抛出:throw, throwsz 异常处理器(exception handler)Try 语句:try 语句包含的代码段表示,如果这段代码出现异常,则会创建一个异常对象并抛出去。
try 程序块–构造一个异常处理器,封装一些可能抛出异常、需要保护的代码try {Java 语句块; //指一个或多个抛出异常的Java 语句}异常(Exception)import java.io.IOException;class Test {public static void main(String args[]) {try {char c = (char)System.in.read();System.out.println(c);} catch (IOException e) {System.out.println(e);}}}异常(Exception)try语句块定义了异常处理器的范围catch语句块捕捉try语句块抛出的异常try {// Code that might generate exceptions} catch(Type1 id1) {// Handle exceptions of Type1} catch(Type2 id2) {// Handle exceptions of Type2} catch(Type3 id3) {// Handle exceptions of Type3}// etc ...异常(Exception)finally语句块–There’s often some piece of code that you want to execute whether or not anexception is thrown within a try block.–无论try中的代码是否产生异常,finally语句块在异常处理中是必须执行的语句块清理现场–关闭打开的文件–关闭网络连接throwTry语句是被动产生异常。
Throws和throw语句是主动产生(抛出)异常,这个异常被catch捕获或是传给它的调用者来处理异常,一般抛出的异常是更加具体的异常子类。
throw语句一定是抛出一个异常对象:throw new Exception(“Something really badhappened.”);throwsz 如果本方法可能产生某些异常,而在方法内部又不想处理这些异常,则可以使用throws 语句把这个异常抛给调用者来处理这些异常。
zString myGetLine( ) throws IOException { ... }z 调用者必须处理这些异常,或是把这些异常再抛给(throws)void parseObj(String s) throws NullPointerException {if (s == null)……;}异常(Exception)自定义异常类必须是ng.Exception类的子类–ng.Exception类的两个构造方法–Exception()Constructs a new exception with null as its detail message.–Exception(String message)Constructs a new exception with the specified detail message.自定义异常类可以不定义构造方法–SimpleException() { super(); }自定义异常类定义自已的构造方法自定义的异常类z You can define new Exception classes.class FileFormatException extends IOException{ // default constructorpublic FileFormatException() {}//constructor contains a detailed messagepublic FileFormatException(String message){ super( message );}z New Exception class must be subclass of Throwable z Most programs throw and catch objects that derive from the Exception classJava Exception Class hierarchyThrowableError ExceptionRuntimeException Must be caughtNeed not be caughtng.Throwablez Throwable: the superclass of all errors and exceptions class. Two subclass:z只有Throwable的子类才能被JVM作为异常抛出或是使用throw语句抛出。