java 字符串异常_java的异常抛出和String类常用方法

一、异常抛出

异常是程序的异种非错误的意外情况,分为运行期异常(RuntimeException)和编译期异常(CheckedExcption)

处理异常可以用try——catch或自定义

1 import java.lang.Exception; //导入异常包

2

3 public classThrowExceptionTest {4 public static void main(String[]args) throwsException{5 try{6 throwExceptionAction();7 int a = 9/0;8 throw new Exception(); //如有异常抛出

9 }10 catch(Exception e){11 throw e; //层层抛出异常

12

13 }14

15 }16

17 private static void throwExceptionAction() {//方法封装

18 try{19 //可能存在异常的程序段,如有异常则抛出并暂停

20 System.out.println("开始");21 int a = 2/0; //数学异常

22 System.out.println(a);23 }24 catch(Exception e){ //如无异常,不执行此块25 //接收抛出的异常

26 System.out.println("出现了异常!");27 System.out.println(e);28 }29 finally{30 //始终执行的程序块

31 System.out.println("始终执行!");32 }33 }34

35 }

二、String的常用方法

public class StringAction{

public static void main(String [] args){

char[] arr = {'b','c','d','e','f','好'};

String a = " 97 好 98 92 10 0 ";

char b = a.charAt(3);//索引3的char值

System.out.println("1"+"\t"+b);

int c = a.indexOf(",");//第一次出现“,”的索引

System.out.println("2"+"\t"+c);

int d = a.charAt(3);//指定索引3的unicode代码点

System.out.println("3"+"\t"+d);

System.out.println("4"+"\t"+a.concat("天很热,想跳河!"));//将指定字符串连接到此字符串的末尾

String e = a.concat("天很热,想跳河!");

String str = a.copyValueOf(arr);//指定char数组中包含该字符序列的String

System.out.println("5"+"\t"+str);

System.out.println("6"+"\t"+a.length()); //字符串的长度

a.replace("9", "*");//替换字符串中的指定字符

System.out.println("7"+"\t"+a.replace("9", "*"));

e.subSequence(1,7);//返回一个由e字符串的第1+1位到第7位组成的字符串

System.out.println("8"+"\t"+e.subSequence(1,7));

arr =a.toCharArray();

System.out.print("9\t");

System.out.println(arr);//将字符串转换成字符数组

e.toString();

System.out.println("10"+"\t"+e.toString());//返回本身

System.out.println("11\t"+a.trim());//忽略前后空白

System.out.println("12\t"+a.trim().length());//忽略后的长度

System.out.println("13\t"+a.valueOf(1==2));//boolean类型的字符串表示形式

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值