java文件里有多个异常,用try-catch处理时有一段代码直接忽略了,调试时没有异常显示,怎么改,求指教怎么改 i
java文件里有多个异常,用try-catch处理时有一段代码直接忽略了,调试时没有异常显示,怎么改,求指教怎么改
import java.lang.Object;
import java.util.Vector;
class EmptyStackException extends Exception
{
public EmptyStackException(String message)
{
super(message);
}
}
class FullStackException extends Exception
{
public FullStackException(String message)
{
super(message);
}
}
public class MyStack <T>
{
Vector<T> vec= new Vector<T>();
public MyStack()
{
int MyStackSize=5;
};
public void push(T item)throws FullStackException
{
if(vec.size()>=5)
{
throw new FullStackException("堆栈满,不可再进行压入。");
}
else
{
vec.add(item);
}
}
public void pop(T item)throws EmptyStackException
{
if(vec.size()==0)
{
throw new EmptyStackException("堆栈空,不可再进行删除。");
}
else
{
vec.remove(item);
}
}
public boolean isEmpty()
{
if(vec.size()==0)
return true;
else
return false;
}
public boolean isFull()
{
if(vec.size()==5)
return true;
else
return false;
}
public void display()
{
for(int i=0;i<vec.size();i++)
{
System.out.print(vec.get(i)+" ");
}
System.out.println();
}
}
class TestMyStack
{
public static void main(String[] args)
{
try
{
MyStack<Integer> s=new MyStack<Integer>();
int i=0;
while(!s.isFull())
{
s.push(i);
i++;
}
s.display();
s.push(5); //异常
while(!s.isEmpty())
{
s.pop(5);
}
s.pop(5); //异常
}
catch (EmptyStackException e)
{
System.out.println("异常信息是:\n" + e.toString());
}
catch (FullStackException e)
{
System.out.println("异常信息是:\n" + e.toString());
}
}
}
java 异常处理
[解决办法]你现在就是catch ..catch的啊!
import java.lang.Object;
import java.util.Vector;
class EmptyStackException extends Exception {
public EmptyStackException(String message) {
super(message);
}
}
class FullStackException extends Exception {
public FullStackException(String message) {
super(message);
}
}
public class MyStack<T> {
Vector<T> vec = new Vector<T>();
public MyStack() {
int MyStackSize = 5;
};
public void push(T item) throws FullStackException {
if (vec.size() >= 5) {
throw new FullStackException("堆栈满,不可再进行压入。");
} else {
vec.add(item);
}
}
public void pop(T item) throws EmptyStackException {
if (vec.size() == 0) {
throw new EmptyStackException("堆栈空,不可再进行删除。");
} else {
vec.remove(item);
}
}
public boolean isEmpty() {
if (vec.size() == 0)
return true;
else
return false;
}
public boolean isFull() {
if (vec.size() == 5)
return true;
else
return false;
}
public void display() {
for (int i = 0; i < vec.size(); i++) {
System.out.print(vec.get(i) + " ");
}
System.out.println();
}
}
class TestMyStack {
public static void main(String[] args) {
MyStack<Integer> s = new MyStack<Integer>();
int i = 0;
try {
while (!s.isFull()) {
s.push(i);
i++;
}
s.display();
s.push(5); // 异常
while (!s.isEmpty()) {
s.pop(5);
}
s.pop(5); // 异常
} catch (FullStackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EmptyStackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[解决办法]将同一个方法里的代码放在一个try中。异常用Exception。这样的话整个方法只需要处理一次。