异常处理、递归和单体程序设计

异常处理

异常有两类:Error 和 Exception。我们能捕捉到的是Exception,Error没办法处理。
异常处理有异常捕捉和异常转移两种方式。

异常捕捉例程:main方法内捕捉异常

public class J_Exception{
	public static void main(String args[ ]){
		try{
			System.out.println("try 语句块");
			throw new Exception();
		}
		catch(Exception e){
			System.err.println("catch 语句块");
			e.printStackTrace();
		}
		finally{
			System.out.println("finally 语句块");
		}
	}
}


finally里不管有没有异常都要执行的。

异常转移例程:一般方法处理异常,首先继承异常类,再抛出异常



public class J_Exception{

	public void fun() thows Exception{	//一般方法捕捉异常
		throw new SimpleException("throwing from fun");
	}
	public static void main(String args[ ]){
		try{
			J_Exception j = new J_Exception();
			j.fun();
		}
		catch(Exception e){
			System.err.println("catch 语句块");
			e.printStackTrace();
		}
		finally{
			System.out.println("finally 语句块");
		}
	}
}

自定义异常:

class J_ExceptionNew extends Exception{	//自定义异常类
	private static int m_number = 0;
	public J_ExceptionNew(){
		m_number ++;
	}

	public  String toString({
		return ("新异常出现的" + m_number + "次数");
	}
}

public class J_ExceptionNewExample
{
	public static void main(String args[ ]){
		try {
			throw new J_ExceptionNew();
		}
		catch(J_ExceptionNew e){
			System.err.println(e);
		}
	}
}

递归方法:自身方法调用自身方法。
递归方法:一个大问题分解为一个整体中问题和一个小问题。

//汉诺塔问题
public void J_Hanoi{
	public static void mb_hanoi(int n,char start,char temp,char end){
		if(n<=1)
			System.out.println("将盘从" + start + "移到" + end);
		else{
			mb_hanoi(n-1,start,end,temp);
			System.out.println("将盘从" + start + "移到" + end);
			mb_hanoi(n-1,temp,start,end);
		}
	}

	public static void main(String args[ ]){
		mb_hanoi(3,'S','T','E');
	}
}

单体类Runtime

单体类java.lang.Runtime 为java应用程序提供一些运行环境接口,例如查询java虚拟机的内存使用情况等。
java.lang.Runtime的成员方法:
public static Runtime getRuntime()	//返回对象的引用值
public int availableProcessors()  //求计算机处理器的个数
public Processexec(String command) throw IOException	//启动外部的程序
r.exec("cmd /c start dir");	//启动一个DOS窗口
r.exec("notepad");	//启动记事本程序
public void gc()	//要求系统尽快进行垃圾回收
public long freeMemory()	//空闲内存的大致字节数
public long totalMemory()	//java 虚拟机所占用的内存字节数
public long maxMemory()	//java 虚拟机可以用的最大内存字节数
public class J_RuntimeExample{
	public static void main(String args[ ]){
		Runtime r = Runtime.getRuntime();
		System.out.println("处理器的个数是" + r.availableProcessors());
		try {
			r.exec("cmd /c start dir");
			r.exec("notepad");
		}
		catch(Exception e){
			System.out.println("命令运行不正常!");
			e.printStackTrace();
		}
		System.out.println("可用的最大内存为: " + r.maxMemory());
		System.out.println("现在的总内存为:" +r.totalMemory());
		System.out.println("现在空闲内存为:" + r.freeMemory());
		r.gc();
		System.out.println("现在空闲内存为:" + r.freeMemory());
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值