# Function: try()

Executes a function that may throw and wraps the result in a [Result](../types/Result.Result.md) or [ResultAsync](../types/Result.ResultAsync.md).

You can use either a custom `catch` handler or rely on the `safe: true` option
to assume the function cannot throw.

## Type Param

**T**

The function type to execute (sync or async) or a Promise type.

## Type Param

**E**

The error type to return if `catch` is used.

## Examples

**Sync try-catch**

```ts
import { Result } from '@praha/byethrow';

const result = Result.try({
  try: () => {
    const x = Math.random() * 10 - 5;
    if (x < 0) throw new Error('Negative!');
    return x * 2;
  },
  catch: (error) => new Error('Oops!', { cause: error }),
});

// result is Result<number, Error>
```

**Sync safe**

```ts
import { Result } from '@praha/byethrow';

const result = Result.try({
  safe: true,
  try: () => Math.random() + 1,
});

// result is Result<number, never>
```

**Async try-catch**

```ts
import { Result } from '@praha/byethrow';

const result = Result.try({
  try: () => fetch('/api/data'),
  catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
```

**Async safe**

```ts
import { Result } from '@praha/byethrow';

const result = Result.try({
  safe: true,
  try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
```

## Call Signature

> **try**\<`T`, `E`>(`options`): [`ResultAsync`](../types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `E`>

### Type Parameters

#### T

`T` _extends_ () => `Promise`\<`any`>

#### E

`E`

### Parameters

#### options

##### catch

(`error`) => `E`

##### try

`T`

### Returns

[`ResultAsync`](../types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `E`>

## Call Signature

> **try**\<`T`>(`options`): [`ResultAsync`](../types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `never`>

### Type Parameters

#### T

`T` _extends_ () => `Promise`\<`any`>

### Parameters

#### options

##### safe

`true`

##### try

`T`

### Returns

[`ResultAsync`](../types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `never`>

## Call Signature

> **try**\<`T`, `E`>(`options`): [`Result`](../types/Result.Result.md)\<`ReturnType`\<`T`>, `E`>

### Type Parameters

#### T

`T` _extends_ () => `any`

#### E

`E`

### Parameters

#### options

##### catch

(`error`) => `E`

##### try

`T`

### Returns

[`Result`](../types/Result.Result.md)\<`ReturnType`\<`T`>, `E`>

## Call Signature

> **try**\<`T`>(`options`): [`Result`](../types/Result.Result.md)\<`ReturnType`\<`T`>, `never`>

### Type Parameters

#### T

`T` _extends_ () => `any`

### Parameters

#### options

##### safe

`true`

##### try

`T`

### Returns

[`Result`](../types/Result.Result.md)\<`ReturnType`\<`T`>, `never`>
