• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by user-759 (yahoo) · Jan 04, 2010 at 09:16 PM · iphone

How do you cleanly capture exceptions ? Console throws NullReferenceException

I understand from the documentation that FindWithTag should just return false if the object hasn't been created yet. But it throws a NullReferenceException instead.

e.g

var newBullet : Transform;

newBullet = GameObject.FindWithTag("bullet").transform;

if (newBullet) { // Do something with bullet } else { // Do something knowing the bullet isn't on screen. }

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
7

Answer by Murcho · Jan 04, 2010 at 11:12 PM

Your NullReferenceException there isn't coming from your if/else statement, but from the assignment of newBullet. FindWithTag returns Null, not false, if it fails to find an object of that tag, and so you are attempting to get the transform of a null GameObject. The following code should do the checks properly.

var newBullet : Transform; var newBulletObject : GameObject;

newBulletObject = GameObject.FindWithTag("bullet");

if (newBulletObject != null) { newBullet = newBulletObject.transform; // Do something with bullet } else { // Do something knowing the bullet isn't on screen. }

The safer and less laborious way of doing these tests is with try/catch statements. These "try" to execute a piece of code, then "catch" any exceptions that fall through. I'm unsure if they are available in the JavaScript (UnityScript) implementation, however here is an example in C#.

Transform newBullet;
try
{
    // Attempt to do everything in one line.
    newBullet = GameObject.FindWithTag("bullet").transform;
    // Do something with bullet
}
catch(Exception e)
{
    // Something went wrong, so lets get information about it.
    Debug.Log(e.ToString());
    // Do something knowing the bullet isn't on screen.
}

This code will attempt to execute your assignment of newBullet, and if there are any exceptions thrown, it will fall into the catch statement and print the Exception information to the debug console. The Exception class I've used there is a catch all, and if you are expecting a more specific exception to be thrown, you can put another catch statement in there, replacing Exception with say NullReferenceException.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image user-759 (yahoo) · Jan 15, 2010 at 12:08 AM 0
Share

Spot on !. Of course I'm referencing a Null. Thanks very much indeed.

avatar image cregox · Oct 14, 2011 at 06:39 PM 2
Share

you just forgot to mention `Exception` needs using System or simply using it as catch (System.Exception e). Also, linking to original documents is always recommended! ;)

avatar image
3

Answer by jconde · Apr 30, 2010 at 04:12 PM

The only difference in Javascript is that it's catch(e:Exception) or just catch(e). Otherwise it works the same way.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by David_29 · Jun 09, 2017 at 09:00 PM

@user-759 (yahoo)

Read it all before you conclude it.

I see that there's an accepted answer. But, there is a better answer for handling NullReferenceExcep[tion. If you can relate programming in Java language like me, you can prevent from sending a null error by using the try-catch block. Try it for yourself! ;-)

If you're using in C#, check if you have using System; at the top of your script file. If not, add it. Now, you can use all sorts of Exception classes while try-catching a line of code.

If your're using Javascript, use import System;

Here's an example:

 using System; // --> This exact line of code. That's it.
 using UnityEngine;
 
 public class Test : MonoBehaviour {
 
     public GameObject player; // --> Example to check if there's a null content;
 
     public void Update() {
 
         // You may now catch null reference here.
         try {
 
             player.transform.Translate(0, 0, 2);
 
         } catch(NullReferenceException e) {
 
         }
 
     }
 
 }

Also remember, you can catch also other exceptions such as MissingReferenceException, MissingComponentException, IndexOutOfRangeException, or any other exception classes as long as you include using System in your script. That is all.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

Rotating a camera based on TouchPad input. 3 Answers

where to find info on Boundary variable type? 1 Answer

high score name entry iphone 1 Answer

Help Marshal.StructureToPtr only IOS platform problem 0 Answers

altimeter gauge... 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges