Java try catch
Java try catch
/*
异常处理的捕捉形式:
这是可以对异常进行针对性处理的方式。
具体格式是:
try
//需要被检测异常的代码。
catch(异常类 变量)//该变量用于接收发生的异常对象
//处理异常的代码。
//一定会被执行的代码。
异常处理的原则:
1,函数内容如果抛出需要检测的异常try catch throw php,那么函数上必须要声明。
否则必须在函数内用捕捉,否则编译失败。
2,如果调用到了声明异常的函数,要么要么,否则编译失败。
3,什么时候catch,什么时候 呢?
功能内容可以解决try catch throw php,用catch。
解决不了,用告诉调用者,由调用者解决 。
4,一个功能如果抛出了多个异常Java try catch,那么调用时,必须有对应多个catch进行针对性的处理。
内部又几个需要检测的异常try catch throw php,就抛几个异常,抛出几个Java try catch,就catch几个。
class FuShuIndexException extends Exception
{
FuShuIndexException()
{}
FuShuIndexException(String msg)
{
super(msg);
}
}
class Demo
{
public int method(int[] arr,int index)//throws NullPointerException,FuShuIndexException
{
if(arr==null)
throw new NullPointerException("没有任何数组实体");
if(index<0)
throw new FuShuIndexException();
return arr[index];
}
}
class ExceptionDemo4
{
public static void main(String[] args)
{
int[] arr = new int[3];
Demo d = new Demo();
try
{
int num = d.method(null,-1);

System.out.println("num="+num);
return;
}
catch(NullPointerException e)
{
System.out.println(e.toString());
return;
}
catch (FuShuIndexException e)
{
System.out.println("message:"+e.getMessage());
System.out.println("string:"+e.toString());
e.printStackTrace();//jvm默认的异常处理机制就是调用异常对象的这个方法。
System.out.println("负数角标异常!!!!");
}
/*
catch(Exception e) //多catch父类的catch放在最下面。
{
System.out.println(e);
}
finally //一定会执行的代码
{
System.out.println("finally");
}
*/
System.out.println("over");
}
}
/*
try catch finally 代码块组合特点:
1,
try catch finally
2,
try catch(多个)当没有必要资源需要释放时,可以不用定义finally。
3,
try finally 异常无法直接catch处理,但是资源需要关闭。
*/
class FushuException extends Exception
{
public FushuException(String s)
{
super(s);
}
}

class Person
{
int age;
String name;
public Person(String name,int age)
{
this.name = name;
this.age = age;
}
public Person()
{
}
public int method(int[] arr,int index) throws FushuException
{
if(arr == null)
{
throw new NullPointerException("数组不能为null");
}
if(index arr.length)
{
throw new ArrayIndexOutOfBoundsException("数组下标越界 ");
}
return arr[index];
}
}
public class FieldDemo
{
public static void main(String[] args) throws FushuException
{
Person person = new Person("Tom", 50);
int[] arr = {1,2,3};
try {
int rel = person.method(arr, -2);
System.out.println(rel);
}
finally
{
System.out.println("finally");
}
System.out.println("over");
}
}
公告:
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299
资源库 - 资源分享下载网 » Java try catch
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299
资源库 - 资源分享下载网 » Java try catch
常见问题FAQ
- 关于资源售价和售后服务的说明?
- 代码有没有售后服务和技术支持?
- 有没有搭建服务?
- 链接地址失效了怎么办?
- 关于解压密码

