字符串名称 = 空;
名称.ToLower();
在大多数语言中,这样的代码可以编译。哪些语言会在编译时捕获此类错误?
直到现在我知道的唯一一个是榆树:http://elm-lang.org
最佳答案
Rust防止在编译时出现很多错误。 Rust 没有运行时异常(除了 panic!
会导致程序崩溃),而是使用返回值进行错误处理。
let name = None; // error: mismatched types
let name: Option<String> = None; // ok
name.to_lowercase(); // error: no method named `to_lowercase` found for type `Option`
// correct:
match name {
None => { /* handle None */ },
Some(value) => { value.to_lowercase(); },
}
// or to ignore None and crash if name == None
name.unwrap().to_lowercase();
其他语言没有的 Rust 核心概念之一(afaik)是 lifetimes ,这可以防止在编译时悬空引用。然而,这是垃圾收集和引用计数语言不需要的东西。
Go没有异常(exception)。与 Rust 一样,它使用返回值来表示错误。但它不是空安全的:
// strings can't be nil:
var name string = nil // error: cannot use nil as type string in assignment
// string pointers can:
var name *string = nil // ok
string.ToLower(*name) // panic: runtime error: invalid memory address
以下语言确实有异常处理,但可能仍然有助于回答问题。
Swift也比一般情况更安全,但它确实包括运行时异常。但是,Swift 的异常比 C++、Java、C# 等的异常更明确(例如,您必须在每次调用抛出函数前加上
try
前缀,并且函数声明必须指定该函数是否可以抛出)。let name = nil // error: type of expression is ambiguous without more context
let name: String? = nil // ok
name.lowercaseString // error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
name!.lowercaseString // will crash at runtime with: fatal error: unexpectedly found nil while unwrapping an Optional value
name?.lowercaseString // calls method only if name != nil
Kotlin是一种更安全的 JVM 语言,它也可以编译为 JavaScript。 Kotlin 也有异常(exception)。
val name = null
name.toLowerCase() // compile-error
if (name != null)
name.toLowerCase() // ok
name?.toLowerCase() // call only if non-null
Ada是一种专为安全关键目的而设计的语言。根据 http://www.adaic.org/advantages/features-benefits/ ,它的“许多内置检查允许编译器或链接器检测在基于 C 的语言中只能在运行时捕获的错误”。
关于exception - 哪些编程语言没有运行时异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35343584/