1.用try --catch处理异常
适合处理程序员可以控制和用户输入有误的情况,以起到程序来发顺利进行和避免不必要情况的发生
try{
//如果里面有异常就执行catch里的语句
}catch(Exception e){//exception
}
2.用throws处理异常
throws是处理异常的两种方法之一,它的处理方法是将异常抛给上一级处理,如都不能处理,最终抛给虚拟机处理,这个过程我们称为抛异常。这种方法适合比较严重的异常和程序员无法预料或无法完全避免异常发生的情况,以及无法处理的异常。
都是用在方法中
import java.util.*;
class A{
void a() throws Exception //往上抛
{
int a,b,c;
Scanner in=new Scanner(System.in);
a=in.nextInt();
b=in.nextInt();
c=a%b;
System.out.println(c);
}
}
public class Throws {
public static void main(String[] args)//throws Exception 抛到虚拟机
{
// TODO Auto-generated method stub
A aa=new A();
try{
aa.a();//调用A里面的a
}catch(Exception e){
System.out.println("输入有误");
}
System.out.println("顺利进行");
}
}
3.Finally 的用法
Finally语句是起到异常出口的作用,用在try..catch语句的最后,无论是否出现异常(catch中的语句是否被执行),finally中的语句都会被执行,这样可以更好的控制程序的走向。
import java.util.*;
class A{
void a() //throws Exception //往上抛
{
int a,b,c;
Scanner in=new Scanner(System.in);
a=in.nextInt();
b=in.nextInt();
c=a%b;
System.out.println(c);
}
}
public class Throws {
public static void main(String[] args)//throws Exception 抛到虚拟机
{
// TODO Auto-generated method stub
A aa=new A();
try{
aa.a();//调用A里面的a
}catch(Exception e){
System.out.println("输入有误");
}
finally{//无论是否出现异常(catch中的语句是否被执行),finally中的语句都会被执行
System.out.println("顺利进行");
}
}
}
4.equlas方法(1)
java中一般情况下,不可以再用==来比较是否相等的情况,而是要用equals方法来比较,equals方法属于object类并且不是final类型,所以任何类都可以继承并且覆盖该方法。
package zhou.fei;
class B{
private int i;
B(int i){
this.i=i;
}
public boolean equals(B b2){
//两个对象的i进行比较
if(this.i==b2.i)
return true;
else
return false;
}
}
public class Equals1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
B b1=new B(20);
B b2=new B(20);
//System.out.println(b1==b2);
//对象之间不可以再用“==”来进行比较。因为这样比较的对象的内存地址。而不是对象中的具体属性。
System.out.println(b1.equals(b2));
//覆盖后的equals方法比较的不再是两个对象的内存