Java代码从未在try-catch中输入try块



我目前正在创建一个项目,以编写一个客户端和服务,从音乐数据库中提供信息。

我创建了一个MusicService.java文件,该文件部署良好。然而,我不确定代码是否正确。然后我需要创建一个客户端。当我运行客户端时,我的MusicService.java类中的try-catch不断抛出错误错误,说("Unable to find composer"(或("Cannot find disc"(通过进行一些基本的调试,我知道getByComposer和getByDisc中的try方法从未被输入并直接进入catch。

我还知道,在我的client.java方法中,由于我的print语句在控制台中返回,所以正在输入try。然而,代码从来没有执行过,直接进入catch异常,我不知道为什么。

我知道某个地方有个错误,也许我没有打电话,但我已经花了几个小时,似乎找不到问题所在。

我将在下面留下这两种方法,如果有人能帮忙,我将不胜感激。

MusicService.java方法

package music;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MusicService extends MusicServiceSkeleton {
private final static String databaseHost = "mysql0.cs.stir.ac.uk";
private final static String databaseName = "CSCU9YW";
private final static String databasePassword = "rtk1";
private final static String databaseUser = "rtk1";
private final static String discTable = "music";

//define methods to implement the WSDL opeartions getByComposer() and getByDisc()
public music.MultipleTracks getByComposer(music.Composer composer)throws ErrorFault
{
try {
TrackDetail[]info=getByField("composer",composer.getComposer());
MultipleTracks multiTrack = new MultipleTracks(); 
TrackDetails multiRetrieve = new TrackDetails(); 
multiRetrieve.setTracklist(info);
multiTrack.setMultipleTracks(multiRetrieve);
return multiTrack;
}
catch(Exception e)
{
throw(new ErrorFault("Unable to find composer"));
}
}
public music.MultipleTracks getByDisc(music.Disc disc)throws ErrorFault
{
try {
System.out.println("hello in getbbydisc");
TrackDetail[]info=getByField("disc",disc.getDisc());
MultipleTracks multiTrack = new MultipleTracks(); 
TrackDetails multiRetrieve = new TrackDetails(); 
multiRetrieve.setTracklist(info);
multiTrack.setMultipleTracks(multiRetrieve);
return multiTrack;
}
catch(Exception e)
{
throw(new ErrorFault("Unable to find disc"));
}
}

private TrackDetail[] getByField(String field, String value) throws ErrorFault {
try {
if (value.length() == 0)
throw (new Exception(field + " is empty"));
Class.forName("com.mysql.jdbc.Driver").newInstance();
String databaseDesignation = "jdbc:mysql://" + databaseHost + "/" + databaseName + "?user=" + databaseUser
+ "&password=" + databasePassword;
Connection connection = DriverManager.getConnection(databaseDesignation);
Statement statement = connection.createStatement();
String query = "SELECT disc, track, composer, work, title " + "FROM " + discTable + " " + "WHERE " + field
+ " LIKE '%" + value + "%'";
ResultSet result = statement.executeQuery(query);
result.last();
int resultCount = result.getRow();
if (resultCount == 0)
throw (new Exception(field + " '" + value + "' not found"));
TrackDetail[] trackDetails = new TrackDetail[resultCount];
result.beforeFirst();
int resultIndex = 0;
while (result.next()) {
TrackDetail receiver = detailsReceived(result);
trackDetails[resultIndex++]= receiver;
}
connection.close();
return (trackDetails);
} catch (Exception exception) {
String errorMessage = "database access error - " + exception.getMessage();
throw (new ErrorFault(errorMessage, exception));
}
}
private TrackDetail detailsReceived(ResultSet current)throws SQLException
{
TrackDetail details = new TrackDetail();
details.setDiscNumber(current.getString(1));
details.setTrackNumber(current.getString(2));
details.setComposerName(current.getString(3));
details.setWorkName(current.getString(4));
details.setTitleName(current.getString(5));
return details;
}
}

Client.java方法


package music;
import music.MusicServiceStub.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame implements ActionListener {
private final static int contentInset = 5;
private final static int trackColumns = 130;
private final static int trackRows = 20;
private final static int gridLeft = GridBagConstraints.WEST;
private final static String programTitle = "Music Album";
private GridBagConstraints contentConstraints = new GridBagConstraints();
private GridBagLayout contentLayout = new GridBagLayout();
private Container contentPane = getContentPane();
private JButton discButton = new JButton("Check");
private JLabel discLabel = new JLabel("Disc Number:");
private JTextField discText = new JTextField(5);
private JButton nameButton = new JButton("Check");
private JLabel nameLabel = new JLabel("Composer/Artiste Name:");
private JTextField nameText = new JTextField(16);
private Font trackFont = new Font(Font.MONOSPACED, Font.PLAIN, 12);
private JLabel trackLabel = new JLabel("Tracks:");
private JTextArea trackArea = new JTextArea(trackRows, trackColumns);
private JScrollPane trackScroller = new JScrollPane(trackArea);
private MultipleTracks tracks;

// define here private variable for your Client Stub

public Client() throws Exception  {
contentPane.setLayout(contentLayout);
addComponent(0, 0, gridLeft, nameLabel);
addComponent(1, 0, gridLeft, nameText);
addComponent(2, 0, gridLeft, nameButton);
addComponent(0, 1, gridLeft, discLabel);
addComponent(1, 1, gridLeft, discText);
addComponent(2, 1, gridLeft, discButton);
addComponent(0, 2, gridLeft, trackLabel);
addComponent(0, 3, gridLeft, trackScroller);
nameButton.addActionListener(this);
discButton.addActionListener(this);
trackArea.setFont(trackFont);
trackArea.setEditable(false);
// instantiate your Client Stub and assign to private class variable declared above
}
public static void main(String[] args) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
Client window = new Client();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setTitle(programTitle);
window.pack();
int windowWidth = window.getWidth();
int windowHeight = window.getHeight();
int windowX = (screenWidth - windowWidth) / 2;
int windowY = (screenHeight - windowHeight) / 2;
window.setLocation(windowX, windowY);
window.setVisible(true);
}
private void addComponent(int x, int y, int position, JComponent component) {
Insets contentInsets = new Insets(contentInset, contentInset, contentInset, contentInset);
contentConstraints.gridx = x;
contentConstraints.gridy = y;
contentConstraints.anchor = position;
contentConstraints.insets = contentInsets;
if (component == trackArea || component == trackLabel)
contentConstraints.gridwidth = GridBagConstraints.REMAINDER;
contentLayout.setConstraints(component, contentConstraints);
contentPane.add(component);
}
public void actionPerformed(ActionEvent event) {
String trackRows = "";
TrackDetail[] tracks;
try {
//System.out.println("Hello");
if (event.getSource() == nameButton)
tracks = getField("composer", nameText.getText());
else if (event.getSource() == discButton)
tracks = getField("disc", discText.getText());
else
return;
trackRows += String.format("%4s %5s %-32s %-40s %-40sn", "Disc", "Track", "Composer/Artist", "Work", "Title");
for (int i = 0; i < tracks.length; i++) {
TrackDetail trackDetail = tracks[i];
trackRows += extractMusicData(trackDetail);

// extract the data for a track and append to trackRows variable

}
} catch (Exception exception) {
String error = exception.getMessage();
if (error == null) error = exception.toString();
error = "could not get track - " + error;
trackRows += error;
}
trackArea.setText(trackRows);
}
private String extractMusicData(TrackDetail track )
{
String albumName= track.getWorkName();
String composer = track.getComposerName();
String title= track.getTitleName();
String trackNo= track.getTrackNumber().toString();
String discNo= track.getDiscNumber().toString();
String extractMusicTracks= String.format("%4s %5s %-32s %-40s %-40sn", discNo, trackNo, composer, albumName, title);
return extractMusicTracks; 
} 
private TrackDetail[] getField(String field, String value) throws Exception {
// define behaviour for method getField() to call the web service methods and receive the results
try 
{
TrackDetail[] multiTrack; 
MusicServiceStub stub=new MusicServiceStub();
if(field.equals("disc"))
{
MusicServiceStub.Disc requestDisc = new MusicServiceStub.Disc(); 
requestDisc.setDisc(value);
MusicServiceStub.MultipleTracks message= stub.getByDisc(requestDisc); 
multiTrack= extractedTracks(message);
return multiTrack; 
} else if(field.equals("composer"));
{
MusicServiceStub.Composer requestComposer = new MusicServiceStub.Composer(); 
requestComposer.setComposer(value);
MusicServiceStub.MultipleTracks message= stub.getByComposer(requestComposer); 
multiTrack= extractedTracks(message);
return multiTrack; 
}
} catch(Exception e)
{
System.out.println(e);
}
return null; 
}

private TrackDetail[] extractedTracks(MultipleTracks tracks)
{
TrackDetails track= tracks.getMultipleTracks();
TrackDetail[] multiTrack= track.getTracklist(); 
return multiTrack;
}
}

您的错误处理还远远不够:

  1. Idiomatic java规定异常以单词"Exception"结尾。不要使用名称"ErrorFault"。除了不地道之外,这是一种重言式。

  2. 重新思考时,传递原因,并丢失parens:throw new ErrorFault("Unable to find composer", e);,除非不要将其命名为ErrorFault。现在您可以检查是什么导致java跳转到catch块。

请注意,java不会无缘无故地随机跳转到捕获块。试块中的某个东西是投掷,而你通过投掷其他东西来隐藏原因,而没有将原始内容作为原因传递。

  1. 永远不要捕捉异常,只需执行"System.out.println(e("-代码将在之后继续,即使进程现在显然处于无效状态。如果您不知道如何处理异常,那么最好在方法上添加一个"throws"子句来继续抛出它。如果这不是一个选项,并且您也不想将其封装在适当的异常中,那么绝对的回退是throw new RuntimeException(e),而不是e.printStackTrace(),或者更糟的是,信息擦除System.out.println(e);-更新IDE的模板

一旦应用了上述建议,问题就应该很清楚了。如果不是,至少现在你得到了一个包含更多细节的堆栈跟踪;把它作为一个问题发布在这里(或更新你的问题(,并附上这些信息,也许有人可以帮你弄清楚发生了什么。

相关内容

  • 没有找到相关文章

最新更新