(一)异常的抛出和处理:
(1)放在main里
package com.tzr.exception;
import java.util.ArrayList;
public class ExceptionDemo01 {
public static void main(String[] args) {
try {
//list目前为空,因为还没有new,是不能使用的
ArrayList<Integer> list = null;//空指针异常
list.add(34);
list.add(344);
}catch(NullPointerException e) {
System.out.println("出现了空指针异常");
throw e;//抛出异常
}
}
}
(2)放在main外
自定义处理异常方法
try {
test(19);
test(0);
test(200);//抛出异常后程序停止运行
test(-90);
test(-9099);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void test(int age) throws Exception {
if(age>=0&&age<18) {
System.out.println("未成年人");
}else if(age>=18&&age<=150) {
System.out.println("成年人");
}else {
throw new Exception("年龄输入不合法"); //抛出异常
}
}
}
(二)JDBC编程
1.建立驱动
2,建立连接
public class JDBCDemo01 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");//使用什么驱动连接什么数据库
//String url="jdbc:mysql://localhost:3306/web01";//有时候可能会乱码
//解决乱码问题
String url="jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8";
String user="root";
String password="root";
Connection con=DriverManager.getConnection(url,user,password);
//DriverManager.getConnection(url,user,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.进行增删改查操作
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");//使用什么驱动连接什么数据库
//String url="jdbc:mysql://localhost:3306/web01";//有时候可能会乱码
//解决乱码问题
String url="jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC";
String user="root";
String password="root";
Connection con=DriverManager.getConnection(url,user,password);
//DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from user");
while(rs.next()) {
System.out.println(rs.getInt(1)+","+rs.getString(2)+rs.getString(3));
}
if(rs!=null)rs.close();
if(stmt!=null)rs.close();
if(con!=null)rs.close();
System.out.println("666");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}