java的异常抛出和String类常用方法

一、异常抛出

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

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

 1 import java.lang.Exception;                        //导入异常包
 2 
 3 public class ThrowExceptionTest {
 4     public static void main(String[]args) throws Exception{
 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"+"	"+b);
		
		int c = a.indexOf(",");					//第一次出现“,”的索引
		System.out.println("2"+"	"+c);
		
		int d = a.charAt(3);					//指定索引3的unicode代码点
		System.out.println("3"+"	"+d);
		
		System.out.println("4"+"	"+a.concat("天很热,想跳河!"));//将指定字符串连接到此字符串的末尾
		String e = a.concat("天很热,想跳河!");
		
		String str = a.copyValueOf(arr);		//指定char数组中包含该字符序列的String
		System.out.println("5"+"	"+str);
		
		System.out.println("6"+"	"+a.length()); 		//字符串的长度
		
		a.replace("9", "*");					//替换字符串中的指定字符
		System.out.println("7"+"	"+a.replace("9", "*"));
		
		e.subSequence(1,7);						//返回一个由e字符串的第1+1位到第7位组成的字符串
		System.out.println("8"+"	"+e.subSequence(1,7));
		
		arr =a.toCharArray();
		System.out.print("9	");
		System.out.println(arr);				//将字符串转换成字符数组
		
		e.toString();
		System.out.println("10"+"	"+e.toString());		//返回本身
		
		System.out.println("11	"+a.trim());			//忽略前后空白
		System.out.println("12	"+a.trim().length());	//忽略后的长度
		
		System.out.println("13	"+a.valueOf(1==2));			//boolean类型的字符串表示形式
   } 
}

  

原文地址:https://www.cnblogs.com/-maji/p/7087006.html