// 工作中使用:
//需求: 统计年龄总和
val list = List("1 zhangsan 20 shenzhen","2 lisi shenzhen"," wagnwu 20 shenzhen","3 zhangsan 20 ")
// 工作中使用:
//需求: 统计年龄总和
println(list.map(line => {
val arr = line.split(" ")
Try(arr(2).toInt).getOrElse(0)
}).sum)
}
package tcode.chapter09
import java.sql.{Connection, DriverManager, PreparedStatement}
import scala.util.Try
object $01_Exception {
/**
* java中的异常处理:
* 1、捕获异常: try{..}catch(..){..}finally{...}
* 2、抛出异常: throw new XXXException + throws XXXException
* scala中异常处理:
* 1、捕获异常:
* 1、try{..}catch{..}finally{...} <用于获取外部资源链接的场景>
* 2、Try(代码块).getOrElse(默认值) 【如果代码块执行成功则返回代码块的执行结果,如果代码块执行失败则返回默认值】 <常用>
* Try有两个子类: Success、Failture
* Success: 代表代码执行成功,代码执行结果封装在Success中
* Failture: 代表代码执行失败
* 2、抛出异常: throw new XXXException [scala中抛出异常不需要在方法名后面通过throws声明异常.scala中没有throws关键字] <不用>
*
*/
def main(args: Array[String]): Unit = {
println(m1(10, 0))
val list = List("1 zhangsan 20 shenzhen","2 lisi shenzhen"," wagnwu 20 shenzhen","3 zhangsan 20 ")
// 工作中使用:
//需求: 统计年龄总和
println(list.map(line => {
val arr = line.split(" ")
Try(arr(2).toInt).getOrElse(0)
}).sum)
}
def m1(a:Int,b:Int) = {
/* if(b==0) throw new Exception("被除数不能为0")
a/b*/
try{
a/b
}catch {
case e:Exception => 0
}finally {
//...
}
}
def jdbc(): Unit = {
var connnection:Connection = null
var statement:PreparedStatement = null
try{
connnection = DriverManager.getConnection("....")
statement = connnection.prepareStatement("insert into person values(?,?,?)")
statement.setString(1,"")
statement.setString(2,"")
statement.setString(3,"")
statement.executeUpdate()
}catch {
case e:Exception =>
}finally {
if(statement!=null)
statement.close()
if(connnection!=null)
connnection.close()
}
}
}