java 异常

时间:2023-03-08 20:34:31
java 异常

1.java异常

java 异常

2.自定义抛出

java 异常

3.运行时异常,程序有问题,让使用者可以改‘

java 异常

4.return  和  throw的区别

return 符合函数要求的值    throw  有问题的时候用它结束

5.

java 异常

6.java编程思想练习题

(1)编写一个类,在其main()方法的try块里抛出一个异常的Exception类的对象。传递一个字符串参数给Exception的构造器。在catch

自居里捕获此异常对象,并且打印字符串参数。添加一个finally自居,打印一条信息证明这里确实得到了执行。

public Class E_01Demo(){
public static void main (String args[]){
try{
throw new Exception("a Exception ");()
}catch(Exception e){
system.err.println("error"+e.getMessage());
}finally{
system.out.println("a finally cause");
}
} }

(2)定义一个对象引用并初始化为null,尝试用词引用调用方法。把这个调用方法写在try-catch的字句里捕获异常。

public class E_02NullException(){
public static void mian(String args[]){
String s = null;
try{
s.toString();
}catch(Exception e){
system.out.println("error+"+e.getMessage());
}
} }

(3)编写能够捕获ArrayIndexOUtofBloundsException的异常的代码

public class E-03Exception(){
public static void main(String args[]){
char[] array = new char[10];
try(){
char[10] = 'x';
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("e = " + e);
}
}
}

(4)使用extends 关键字简历一个自定义异常类。为这个类写一个接受字符串参数的构造器。为此把参数保存在对象内部的字符串引用中,写一个方法显示此字符串。

写一个方法显示字符串。写一个try-catch字句,对这个新异常进行判断。

class MyException extends Exception{
String msg;
public MyException(String msg){
this.msg = msg;
}
public void printMsg(){
System.out.println("msg = "+ msg);
}
} class MyException2 extends(String s){
public MyException2(String s){ super(s);}
} public class E04_Exception(){
public static void main(String args[]){
try{
throw new MyException("MyException message");
}catch(MyException e){
e.printMsg();
}
try{
throw new MyException2("MyException2 message");
}catch(MyException e){
"e.getMessage() = " + e.getMessage());
}
}
}

(5)使用while循环简历类似恢复模型的异常处理行为,它将不断重复,直到异常不再抛出。

class ResumerException extends Exception{}

class Resumer{
static int count = 3;
static void f() throws ResumerException{
if(--count)
throw new ResumerException();
}
} public class E05_Exception{
public void main(String args[]){
while(true){
try{
Resumer.f();
}catch(ResumerException e){
system.out.println("Caught" +e);
continue;
}
System.out.println("Got through...");
break;
}
System.out.println("Successful execution");
}
}/* Output:
Caught exceptions.ResumerException
Caught exceptions.ResumerException
Got through...
Successful execution
*/