try{
int i=10/0;
}catch(Exception e){
System.out.println("处理异常");
}
try{
int i=10/10;
}catch(Exception e){
System.out.println("处理异常");
} finally{
System.out.println("有无异常都会执行");
}
结果:有无异常都会执行。
try{
int i=10/0;
}catch(Exception e){
System.out.println("处理异常");
} finally{
System.out.println("有无异常都会执行");
}
结果:处理异常
有无异常都会执行
try{
int num[]=new int[2] ;
num[0]=10;
num[1]=20;
int n=num[0]/0;//在这里出现异常
num[2]=n;//该语句不会被执行
}catch(IndexOutOfBoundsException e){
System.out.println("数组下标越界");
}catch(ArithmeticException e){
System.out.println("除数为0");
}catch(Exception e) {
System.out.println("exception异常");
}finally{
System.out.println("有无异常都会执行");
}
结果:除数为0
有无异常都会被执行
public class Textclass {
public int Text() {
try {
int num[] = new int[2];
num[0] = 10;
int n = num[0] / 0;
} catch (ArithmeticException e) {
System.out.println("除数为0");
} finally {
System.out.println("有无异常都会执行");
}
return 1;
}
}
public class Testmain {
public static void main(String[] args){
Textclass t=new Textclass();
System.out.println(t.Text());
}
}
结果:除数为0
有无异常都会执行
1
提示:当我们无法判断具体异常类型的时候使用Exception或Throwable代替
public class TextInherit {
public int Text() throws Exception {
int num=10/0;
return num;
}
}
public class Testmain {
public static void main(String[] args) throws Exception {
TextInherit t=new TextInherit();
System.out.println(t.Text());
}
}
package com.company;
public class Myexception extends Exception{
public Myexception(String s){
super(s);
}
}
package com.company;
public class Person {
private char sex;
public void setSex(char sex1) throws Myexception{
if(sex1=='f'||sex1=='m'){
sex=sex1;
}
else{
throw new Myexception("性别错误");
}
}
public char getSex(){
return sex;
}
}
import com.company.Person;
public class Testmain {
public static void main(String[] args) throws Exception {
Person p=new Person();
p.setSex('a');
System.out.println(p.getSex());
}
}
1.赋值常量:
String str1 = “Bluemsun”;
String str2 = “Bluemsun”;
String str3 = “Bluem”+“sun”;
String str 4 = “Bluem”;
String str5 = str4 +”sun“;
System.out.println(str1==str2); //输出trueSystem.out.println(str1==str3); //输出true
System.out.println(str1.equals(str5)); //输出ture
System.out.println(str1 ==str5);//输出false
分析:如果加号两边出现了变量,那么内存将在堆区创建对象导致不相等,而字符串的连接依旧是在常量池中进行查找。equals方法比较的是字符串序列内容。
2.使用new创建对象
String str1 = new String(“Bluemsun”);
注:使用new都会在堆中创建新的对象
String的字符串是不可修改,如果修改会创建新字符串,浪费内存。
StringBuilder的字符串是可以修改的,不会创建新字符串。
创建空值的对象
StringBuilder strb = new StringBuilder();
创建有默认值的对象
StringBuilder strb = new StringBuilder("abc);
1.Date date = new Date(); 获得当前的时间
2.Date date = new Date(long); 指定时间的1900-1-1到现在的毫秒数
Calendar calendar = Calendar.getInstance();
生成随机数
Random random = new Random();
random.nextInt(100); //0 ~ 100间随机整数
系统运行时,获得和系统有关的信息
Runtime rt = Runtime.getRuntime();
怎么说,我感觉要掌握的东西真滴很多,第二周有点点焦头烂额,还有容器那一块的知识还没开始学(等过两天再来写吧…),然后不过对上一节的内容掌握会好很多了现在。这一节的话我觉得异常那方面真的要处理错误的话还是需要更多联系,尤其是throw和throws这两个关键字的应用,然后常用类的话主要还是在记忆这方面吧…总而言之 继续加油吧…ovo