@Override public MessageData updateUserInfoByIDAndName(Integer id, String name) throws Exception { int result = userInfoMapper.updateUserInfoByIDAndName(id, name); if (result == 0) { throw new Exception("用户不存在"); } return MessageData.buildSuccess("修改成功"); } } 解决代码中的问题

时间: 2024-01-28 10:05:55 浏览: 20
这段代码中的问题在于异常处理不够完善,只是抛出了一个普通的Exception,并没有具体说明异常的原因。可以通过自定义异常类来解决这个问题,具体代码如下: ``` public class UserNotFoundException extends Exception { public UserNotFoundException(String message) { super(message); } } ``` 然后在原来的方法中使用自定义异常类来抛出异常,修改后的代码如下: ``` @Override public MessageData updateUserInfoByIDAndName(Integer id, String name) throws UserNotFoundException { int result = userInfoMapper.updateUserInfoByIDAndName(id, name); if (result == 0) { throw new UserNotFoundException("用户不存在"); } return MessageData.buildSuccess("修改成功"); } ``` 这样就可以在抛出异常时具体说明异常的原因了。同时,也建议在调用该方法时对异常进行捕获和处理,以避免程序出现异常而崩溃。
相关问题

将下列java代码改为python代码:blic static void scan(String host, int startPort, int endPort) throws InterruptedException { List<Integer> portList = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(endPort - startPort + 1); for (int port = startPort; port <= endPort; port++) { int finalPort = port; Thread thread = new Thread(new Runnable() { @Override public void run() { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, finalPort), 100); System.out.println("TCP端口" + finalPort + "开放"); portList.add(finalPort); } catch (Exception e) { } try { DatagramSocket dsocket = new DatagramSocket(finalPort); dsocket.close(); } catch (SocketException e) { portList.add(finalPort); System.out.println("UDP端口" + finalPort + "开放"); } latch.countDown(); } }); thread.start(); } latch.await(); portList.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); }

由于Python是一种解释型语言,因此需要使用不同的模块和语言结构来实现相同的功能。以下是一个类似的Python代码: import socket import threading def scan(host, startPort, endPort): portList = [] lock = threading.Lock() def checkPort(port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(0.1) result = sock.connect((host, port)) with lock: portList.append(port) print("TCP端口" + str(port) + "开放") sock.close() except: pass try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(0.1) sock.bind((host, port)) with lock: portList.append(port) print("UDP端口" + str(port) + "开放") sock.close() except: pass threads = [] for port in range(startPort, endPort+1): t = threading.Thread(target=checkPort, args=(port,)) threads.append(t) t.start() for t in threads: t.join() portList.sort() return portList # 示例 if __name__ == "__main__": host = "127.0.0.1" startPort = 1 endPort = 65535 openPorts = scan(host, startPort, endPort) print(openPorts)

Also create a ControllerCreate class that extends Controller.The create method takes as arguments the name of a new library user, a number of books (as a string), and an integer representing the role of user to create (where the integer 0 means a lender and the integer 1 means a borrower). The create method of the controller then transforms the book number from a string to an integer (using the Integer.parseInt static method), creates an object from the correct class (based on the role specified by the user input: lender or borrower) and calls the addUser method of the library to add the new user object to the library. • If no exception occurs then the create method of the controller returns the empty string. • If the constructor of the Borrower class throws a NotALenderException then the create method of the controller must catch this exception and return as result the error message from the exception object. • If the parseInt method of the Integer class throws a NumberFormatException (because the user typed something which is not an integer) then the create method of the controller must catch this exception and return as result the error message from the exception object. Modify the run method of the GUI class to add a ViewCreate view that uses a ControllerCreate controller and the same model as before (not a new model!) Do not delete the previous views. Note: if at the end of Question 7 you had manually added to your library (model object) some users for testing, then you must now remove those users from the run method of the anonymous class inside the GUI class. You do not need these test users anymore because you have now a graphical user interface to create new users! Run your GUI and check that you can correctly use the new view to create different users for your library, with different types of roles. • Check that, when you create a new user, the simple view is automatically correctly updated to show the new total number of books borrowed by all users. • Also use the “get book” view to check that the users are correctly created with the correct names and correct number of books. • Also check that trying to create a borrower with a negative number of books correctly shows an error message. Also check that trying to create a user with a number of books which is not an integer correctly shows an error message (do not worry about the content of the error message). After you created a new user, you can also check whether it is a lender or a borrower using the “more book” view to increase the number of books of the user by a big negative number: • if the new user you created is a lender, then increasing the number of books by a big negative value will work and the number of books borrowed by the user will just become a larger value (you can then check that using the “get book” view); • if the new user you created is a borrower, then increasing the number of books by a big negative value will fail with an error message and the number of books borrowed by the user will not change (you can then check that using the “get book” view). 完成符合以上要求的java代码

Model class: ``` import java.util.ArrayList; public class Library { private ArrayList<User> users; private int totalBooksBorrowed; public Library() { users = new ArrayList<>(); totalBooksBorrowed = 0; } public void addUser(User user) { users.add(user); totalBooksBorrowed += user.getNumberOfBooks(); } public void removeUser(User user) { users.remove(user); totalBooksBorrowed -= user.getNumberOfBooks(); } public ArrayList<User> getUsers() { return users; } public int getTotalBooksBorrowed() { return totalBooksBorrowed; } } ``` User class: ``` public abstract class User { private String name; private int numberOfBooks; public User(String name, int numberOfBooks) { this.name = name; this.numberOfBooks = numberOfBooks; } public String getName() { return name; } public int getNumberOfBooks() { return numberOfBooks; } public void setNumberOfBooks(int numberOfBooks) { this.numberOfBooks = numberOfBooks; } public abstract boolean isLender(); } ``` Lender class: ``` public class Lender extends User { public Lender(String name, int numberOfBooks) { super(name, numberOfBooks); } @Override public boolean isLender() { return true; } } ``` Borrower class: ``` public class Borrower extends User { public Borrower(String name, int numberOfBooks) throws NotALenderException { super(name, numberOfBooks); if (numberOfBooks < 0) { throw new NotALenderException("A borrower can't have a negative number of books!"); } } @Override public boolean isLender() { return false; } } ``` NotALenderException class: ``` public class NotALenderException extends Exception { public NotALenderException(String message) { super(message); } } ``` ViewCreate class: ``` import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ViewCreate extends JPanel implements ActionListener { private JTextField nameField = new JTextField(10); private JTextField numberOfBooksField = new JTextField(10); private JRadioButton lenderButton = new JRadioButton("Lender"); private JRadioButton borrowerButton = new JRadioButton("Borrower"); private ButtonGroup roleButtonGroup = new ButtonGroup(); private JButton createButton = new JButton("Create"); private ControllerCreate controller; public ViewCreate(Model model) { this.controller = new ControllerCreate(model, this); setLayout(new GridBagLayout()); roleButtonGroup.add(lenderButton); roleButtonGroup.add(borrowerButton); lenderButton.setSelected(true); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.anchor = GridBagConstraints.LINE_END; gc.insets = new Insets(5, 5, 5, 5); add(new JLabel("Name: "), gc); gc.gridx++; gc.anchor = GridBagConstraints.LINE_START; add(nameField, gc); gc.gridx = 0; gc.gridy++; gc.anchor = GridBagConstraints.LINE_END; add(new JLabel("Number of books: "), gc); gc.gridx++; gc.anchor = GridBagConstraints.LINE_START; add(numberOfBooksField, gc); gc.gridx = 0; gc.gridy++; gc.anchor = GridBagConstraints.LINE_END; add(new JLabel("Role: "), gc); gc.gridx++; gc.anchor = GridBagConstraints.LINE_START; add(lenderButton, gc); gc.gridx++; add(borrowerButton, gc); gc.gridx = 1; gc.gridy++; gc.anchor = GridBagConstraints.LINE_END; add(createButton, gc); createButton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { String name = nameField.getText(); String numberOfBooksString = numberOfBooksField.getText(); int role = lenderButton.isSelected() ? 0 : 1; String result = controller.create(name, numberOfBooksString, role); JOptionPane.showMessageDialog(this, result, "Result", JOptionPane.INFORMATION_MESSAGE); } } ``` ControllerCreate class: ``` public class ControllerCreate extends Controller { private ViewCreate view; public ControllerCreate(Model model, ViewCreate view) { super(model); this.view = view; } public String create(String name, String numberOfBooksString, int role) { try { int numberOfBooks = Integer.parseInt(numberOfBooksString); User user = null; if (role == 0) { user = new Lender(name, numberOfBooks); } else if (role == 1) { user = new Borrower(name, numberOfBooks); } model.addUser(user); view.updateTotalBooksBorrowed(); return ""; } catch (NumberFormatException e) { return "Invalid number of books!"; } catch (NotALenderException e) { return e.getMessage(); } } } ``` GUI class: ``` import javax.swing.*; import java.awt.*; public class GUI { private JFrame frame = new JFrame("Library"); private Model model = new Library(); private ViewSimple viewSimple = new ViewSimple(model); private ViewGetBook viewGetBook = new ViewGetBook(model); private ViewMoreBook viewMoreBook = new ViewMoreBook(model); private ViewCreate viewCreate = new ViewCreate(model); public GUI() { Container cp = frame.getContentPane(); cp.setLayout(new BorderLayout()); JTabbedPane tp = new JTabbedPane(); tp.addTab("Simple", viewSimple); tp.addTab("Get book", viewGetBook); tp.addTab("More book", viewMoreBook); tp.addTab("Create", viewCreate); cp.add(tp, BorderLayout.CENTER); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); // Remove test users from model model.removeUser(new Lender("John", 2)); model.removeUser(new Borrower("Mary", 3)); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new GUI(); } }); } } ```

相关推荐

最新推荐

recommend-type

Google C++ Style Guide(Google C++编程规范)高清PDF

On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo. Sometimes it makes sense to have pointer (or better, scoped_ptr) members ...
recommend-type

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a
recommend-type

matlab建立计算力学课程的笔记和文件.zip

matlab建立计算力学课程的笔记和文件.zip
recommend-type

FT-Prog-v3.12.38.643-FTD USB 工作模式设定及eprom读写

FT_Prog_v3.12.38.643--FTD USB 工作模式设定及eprom读写
recommend-type

matlab基于RRT和人工势场法混合算法的路径规划.zip

matlab基于RRT和人工势场法混合算法的路径规划.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。