Java异常之初认识

 1 import java.util.*;
 2 public class Demo13{
 3     
 4     
 5     /*Java规定:
 6         1.必须捕获的异常,包括Exception及其子类,但不包括RuntimeException及其子类,这种类型的异常称为Checked Exception。
 7 
 8         2.不需要捕获的异常,包括Error及其子类,RuntimeException及其子类。
 9     */
10     public static void main(String[] args) {
11         byte[] bs = toGBK("中文");
12         System.out.println(Arrays.toString(bs));
13         
14     }
15     
16     public static byte[] toGBK(String s){
17         try{ //用指定编码转换String 为byte[]
18             return s.getBytes("GBK");
19         }catch(Exception e){
20             //如果系统不支持GBK编码,会捕获到Exception
21             System.out.println(e);  //打印异常信息
22             return s.getBytes();  //尝试使用默认编码
23         }
24     }
25 }

 

posted @ 2020-12-27 17:03  dog_IT  阅读(47)  评论(0编辑  收藏  举报