命名空间
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class TryCatchDemo : MonoBehaviour {
Camera camera;
// Use this for initialization
private void Start()
{
Function(3);
}
private void Function (int index) {
camera = Camera.main;
//打印深度
Debug.Log(camera.depth);
string[] names = new string[] { "xiaoming", "xiaohong" };
//尝试执行这段代码
try
{
Debug.Log(names[index]);
}
catch (IndexOutOfRangeException ex)
{
Debug.Log(ex.ToString());
}
catch (NullReferenceException ex)
{
Debug.Log("出现空引用异常,请核验对象是否为空!");
}
}
}
------------------------------------------------------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;public class NameTooLongExcepthion : Exception {
public NameTooLongExcepthion(string content) : base(content) {}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class TryCatchDemo : MonoBehaviour {
Camera camera;
// Use this for initialization
private void Start()
{
Function(3);
ShowYouName("asddfadfaasdfasdfasdfa");
}
private void Function (int index) {
camera = Camera.main;
//打印深度
Debug.Log(camera.depth);
string[] names = new string[] { "xiaoming", "xiaohong" };
//尝试执行这段代码
try
{
Debug.Log(names[index]);
}
catch (IndexOutOfRangeException ex)
{
Debug.Log(ex.ToString());
}
catch (NullReferenceException ex)
{
Debug.Log("出现空引用异常,请核验对象是否为空!");
}
}
private void ShowYouName(string name)
{
if (name.Length <= 10)
{
Debug.Log(name);
}
else {
//抛出异常
throw new NameTooLongExcepthion("名字太长!");
}
}
}