Java 范围尝试/捕获 [英] Java Scope Try/Catch

查看:21
本文介绍了Java 范围尝试/捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 Java 相当陌生,我正在努力更好地理解一些事情.我知道 try/catch 语句变量仅在该语句内具有作用域.我正在尝试学习 java db sql 并且遇到了一个问题.

Fairly new to Java and am trying to better understand a few things. I understand that try/catch statement variables only have scope within that statement. I am trying to learn java db sql and am running into an issue.

final String DB_URL = "jdbc:derby://localhost:1527/Customers";    
Connection conn = DriverManager.getConnection(DB_URL);

这将创建与我的数据库的连接.我需要在 try/catch 语句中使用它.我想在程序结束时再次访问 conn 变量以关闭连接.我试图在我的程序顶部声明这个变量,但它不会让我,因为它需要一个 try/catch.解决这个问题的最佳方法是什么?

This creates the connection with my database. I need to have this in a try/catch statement. I want to access the conn variable again at the end of the program to close the connection. I tried to declare this variable at the top of my program but it won't let me as it needs a try/catch. What is the best way to tackle this?

如下所示,我将其创建为变量.我试图关闭与我的退出按钮的连接,但代码没有得到执行.使用 if 语句,程序不会关闭,也不会触发 System.out.print 消息.连接开始正常但未关闭.

As suggested below I created it as a variable. I am trying to close the connection with my exit button but the code is not getting executed. With the if statement the program doesn't close nor does the System.out.print message fires. The connection is starting OK but not closing.

if (conn != null){
   conn.close();
   System.out.println("Connection Closed");
   System.exit(0);}

推荐答案

你可以通过在 try/catch 块之外声明 Connection 对象来实现,并在 try{}

You could do it by declaring Connection object outside the try/catch block, and creating it within the try{}

final String DB_URL = "jdbc:derby://localhost:1527/Customers";    
Connection conn = null;
try {
     conn = DriverManager.getConnection(DB_URL);
} catch(Exception e) {
  System.out.println("Exception "+e);
}

这篇关于Java 范围尝试/捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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