哪些编程语言没有运行时异常?

时间:2016-02-11 15:36:28

标签: exception strong-typing

string name = null; name.ToLower();

在大多数语言中,这样的代码会编译。哪些语言会在编译时捕获此类错误?

现在我唯一知道的是榆树:http://elm-lang.org

2 个答案:

答案 0 :(得分:13)

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,它可以防止在编译时悬挂引用。然而,这是垃圾收集和参考计数语言不需要的东西。

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也有例外。

val name = null
name.toLowerCase() // compile-error

if (name != null)
    name.toLowerCase() // ok

name?.toLowerCase() // call only if non-null

Ada是一种专为安全起见目的而设计的语言。根据{{​​3}},它的许多内置检查允许编译器或链接器检测基于C语言的错误,这些错误只能在运行时捕获#34;。

http://www.adaic.org/advantages/features-benefits/没有例外。像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

答案 1 :(得分:0)

Here一个语言列表,默认情况下不允许变量为空。

这使得它们更加安全,在编译时阻止所有NullPointerException,并且更清晰,因为您知道在哪里允许传递null而不是在哪里,只需查看代码。 / p>

这些语言中的大多数还提供许多其他编译时安全功能。

相关问题