自定义异常是不可行的 - java [英] Custom exception is not working how it's supposed to - java

查看:176
本文介绍了自定义异常是不可行的 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了2个自定义异常,但其中一个没有做什么,而另一个没有处理问题。



所以我必须读取一个文件这一个:

  WWSW\\\

WW_W\\\

WW_W\\\

WWEW\\\

只有在文件中找到一个字符时才应引发第一个异常 isnt W,S,E,_或\,但由于我无法找到忽略\我已经尝试了几种方法,但没有一个似乎工作,因为我正在将文件内容存储在一个特征数组。



所以如果我有这样的迷宫:

  WWSW 
WW_W
W1_W
WWEW
pre>

如果没有发生,另一个exection应该被提升:所有行都具有相同的字符数。有一个未处理的错误,我没有任何想法为什么会发生,这里是代码:

  public class MazeFileNumCols extends Exception { 
public MazeFileNumCols(int row){super((行没有相同的
数字os字符+\\\
Line:+ row));}


这是主要代码:

  import java.io.File; 
import javax.swing.JFrame;

public class MazeReader extends JFrame {
private static char [] [] Maze;
private static ArrayList< String> mazeBuffer;


public static void readTextFile(String filename)throws MazeFileWrongChar {
startrow = startcol = finishcol = finishrow = -1;
mazeBuffer = new ArrayList< String>();
int numCols = 0;
尝试{
扫描仪文件=新扫描仪(新文件(文件名));
while(file.hasNext()){
String nextLine = file.nextLine();
mazeBuffer.add(nextLine);
if(nextLine.length()> numCols){
numCols = nextLine.length();
}

}
} catch(异常e){
System.out.println(filename +有一个问题);
}
int numrows = mazeBuffer.size();
System.out.println(number of rows:+ numrows +\\\
number of columns:+ numCols);
Maze = new char [numrows] [numCols];
int r_s,c_s,r_e,c_e; (int i = 0; i< numrows; i ++)


String row = mazeBuffer.get(i); (int j = 0; j< numCols; j ++){

if(row.length()> = j){
迷宫[i] [j ] = row.charAt(j);
}
if(Maze [i] [j] ==('S')||迷宫[i] [j] ==('s')){



}
if(Maze [i] [j] ==('E')||迷宫[i] [j] ==('e')){



}

}
}

for(int i = 0; i< Maze.length;对于(int j = 0; j< Maze [i] .length; j ++){
if(Maze [i] [j]!=('S')&&迷宫[i] [j]!=('W')&&迷宫[i] [j]!=('_')&&迷宫[i] [j]!=('E' ){
throw new MazeFileWrongChar(i,j);
}
}
}
int count = 0; (int i = 0; i< Maze.length; i ++){
if(Maze [i] .length!= numCols){
throw new MazeFileNumCols(i)
}

}



}

这里是函数调用的位置:

  import javax.swing。*; 

public class Main {
static MazeReader reader = new MazeReader();

public static void main(String [] args)throws MazeFileWrongChar,MazeFileNumCols {
//在这里编写代码
try {
MazeReader.readTextFile(maze。文本);
reader.printMaze();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
MazeReader view = new MazeReader();
view.setVisible(true );
}
});

} catch(MazeFileWrongChar e){
System.out.println(e.getMessage());
}
catch(MazeFileNumCols e){
System.out.println(e.getMessage());
}
}
}

解决问题的任何帮助

解决方案

由于您的文件需要包含'\''n'像你说的


是的\\\
在这种情况下被鄙视成为一个可见的人物2个characthers



MDoridio


您需要更新支票的逻辑。


  1. 忽略最后两个字符,然后检查为'\',后跟'n '

  2. 添加字符在有效的字符,但这不安全,因为它可以放在任何地方。

  3. 删除该字符串与 s = s.replace(\\ n,); //转义了\

关于评论中说的问题:


这很奇怪,因为当我运行我的代码我得到这个messege:错误:(24,9)java:异常com.migueltavares.MazeFileNumCols从来没有被抛在身上相应的try语句



MDordio


在方法中

  public static void readTextFile(String filename)throws MazeFileWrongChar 
pre>

你正在扔两个 MazeFileWrongChar MazeFileNumCols 没有在声明中添加最后一个:

  public static void readTextFile(String filename)throws MazeFileWrongChar,MazeFileNumCols 

应该首先不编译,因为你抛出一个检查异常 MazeFileNumCols 这个方法没有抓住它。



然后, try block找不到任何方法,将会出现一个 MazeFileNumCols ,解释您的错误。您不能捕获一个从未抛出块语句


的异常

I created 2 custom exceptions but one of them doesnt do what is supposed to and the other is having an unhandled problem.

So i have to read a file like this one:

WWSW\n
WW_W\n
WW_W\n
WWEW\n

And the first exception should be raised only if it finds one character in the file that isnt "W", "S", "E", "_", or "\n" but its getting raised because i cant find a away to ignore the "\n", i have tried several methods but none seems to work because i am storing the file content in a characther array.

So if i have a maze like this one:

WWSW
WW_W
W1_W
WWEW

The other exection is supposed to get raised if this doesnt happen: "all rows have the same number of characters". Having an unhandled error and i dont have any idea why that is happening, here is the code:

public class MazeFileNumCols extends Exception{
    public MazeFileNumCols(int row) { super(("The lines dont have the same 
number os characters" + "\nLine: "+ row));}

}

Here is the main code:

import java.io.File;
import javax.swing.JFrame;

public class MazeReader extends JFrame {
private static char[][] Maze;
private static ArrayList<String> mazeBuffer;


public static void readTextFile(String filename) throws MazeFileWrongChar {
    startrow=startcol=finishcol=finishrow=-1;
    mazeBuffer=new ArrayList<String>();
    int numCols=0;
    try {
        Scanner file=new Scanner(new File(filename));
        while(file.hasNext()) {
            String nextLine=file.nextLine();
            mazeBuffer.add(nextLine);
            if(nextLine.length()>numCols) {
                numCols=nextLine.length();
            }

        }
    }catch(Exception e) {
        System.out.println(filename + "there is a problem");
    }
    int numrows=mazeBuffer.size();
    System.out.println("number of rows: "+ numrows +  "\nnumber of columns: " + numCols);
    Maze=new char[numrows][numCols];
    int r_s,c_s,r_e,c_e;
    for(int i=0;i<numrows;i++) {

        String row = mazeBuffer.get(i);
        for (int j = 0; j < numCols; j++) {

                if (row.length() >= j) {
                    Maze[i][j] = row.charAt(j);
                }
                if (Maze[i][j] == ('S') || Maze[i][j] == ('s')) {



                }
                if (Maze[i][j] == ('E') || Maze[i][j] == ('e')) {



                }

            }
        }

    for(int i=0;i<Maze.length;i++) {
        for(int j=0;j<Maze[i].length;j++) {
            if(Maze[i][j]!=('S') && Maze[i][j]!=('W') && Maze[i][j]!=('_') && Maze[i][j]!=('E')  ) {
                throw new MazeFileWrongChar(i,j);
            }
        }
    }
    int count=0;
    for(int i=0;i<Maze.length;i++) {
            if(Maze[i].length!=numCols) {
                throw new MazeFileNumCols(i);   
            }

    }



    }

And here is where the functions are called:

import javax.swing.*;

public class Main {
static MazeReader reader = new MazeReader();

public static void main(String[] args) throws MazeFileWrongChar,MazeFileNumCols {
    // write your code here
    try {
        MazeReader.readTextFile("maze.txt");
        reader.printMaze();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MazeReader view = new MazeReader();
                view.setVisible(true);
            }
        });

    } catch (MazeFileWrongChar e ) {
        System.out.println(e.getMessage());
    }
    catch(MazeFileNumCols e) {
        System.out.println(e.getMessage());
    }
}
}

Any help solving the problem would be apreciated.

解决方案

Since your file need to include '\' and 'n' like you said

yes the "\n" is soppused to be a visible character in this case 2 characthers

MDoridio

You will need to update the logic of your check.

  1. Ignore the last two character, and check those to be '\' followed by 'n'
  2. Add those character in the valid characters, but this is not safe as it could be place anywhere.
  3. Remove that String with s = s.replace("\\n", ""); //escaped the \

About the problem said in the comment :

well thats weird because when i run my code i get this messege: Error:(24, 9) java: exception com.migueltavares.MazeFileNumCols is never thrown in body of corresponding try statement

MDordio

In the method

public static void readTextFile(String filename) throws MazeFileWrongChar

You are throwing both MazeFileWrongChar and MazeFileNumCols but didn't add the last one in the declaration like :

public static void readTextFile(String filename) throws MazeFileWrongChar, MazeFileNumCols

It should first not compile since you are throwing a checked-exception MazeFileNumCols in this method without catching it.

And then the try block can't find any method that will thow a MazeFileNumCols, explaining your error. You can't catch an exception that is never thrown in the block statement

这篇关于自定义异常是不可行的 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆